Download presentation
Presentation is loading. Please wait.
Published byΜεθόδιος Ἐφραίμ Κουβέλης Modified over 6 years ago
1
Session 4: More on Polymorphism, Array and Exception Handling.
Java Training Session 4: More on Polymorphism, Array and Exception Handling.
2
Overview Run-Time Polymorphism Downcasting and instanceof
Object.toString() Abstract Class and Abstract Method. Interface Array Exception Handling.
3
Run-Time Polymorphism
We can point a Subclass with a Superclass object. Student sStudent = new ScienceStudent("Rifat", 84, 92); Student bStudent = new BiologyStudent("Tanvir", 100, 105, 79); Possible!! This feature is called “RUN-TIME POLYMORPHISM”
4
Example public class StudentPolymorphismTest { public static void main(String[] args) { Studentstudent1 = new Student("Fahad"); Student student2 = new ScienceStudent("Rifat", 84, 92); Student student3 = new CommerceStudent("Ovi", 94, 96); Student student4 = new BiologyStudent("Tanvir", 100, 105, 79); Student student5 = new ComputerStudent("Fahim", 100, 105, 89); student1.print(); student2.print(); student3.print(); student4.print(); student5.print(); } Output: Student Name: Fahad Student Name: Rifat Physics: 84 Chemistry: 92 Student Name: Ovi Economics: 94 Accounting: 96 Student Name: Tanvir Physics: 100 Chemistry: 105 Biology: 79 Student Name: Fahim Computer: 89
5
Using Superclass References to Point to Subclass Objects
We can point to a subclass object with a superclass reference. But the reverse is not true. Using the superclass reference we can call all the public methods that the subclass inherits from the superclass or overrides according to its need. That means using the superclass reference we can call only those public methods whose signature is present in the superclass or in the superclass of the superclass up to class “Object”.
6
Using Superclass References to Point to Subclass Objects (contd.)
Using the superclass reference (pointing a subclass object) we will not be able to call a method that is defined in the subclass and which is not present as a public method in the superclass. But Java internally tracks the type of every object and call the appropriate method of each object.
7
Using Superclass References to Point to Subclass Objects (contd.)
But only superclass’ methods could be called. Student student = new ScienceStudent("Rifat", 84, 92); student.getName(); //valid student.getChemistry(); //compiler error!! student.getPhysics(); //compiler error!! Internally ‘student’ variable points to a ScienceStudent but it can’t be used to call subclass’s methods. Any solution? Casting more specificalyDowncasting!!
8
Downcasting Like integer to double or bool to integer, object reference can also be type casted. When a superclass reference is casted to subclass reference it is called down casting. ScienceStudentscienceStudent = (ScienceStudent) student; scienceStudent.getName(); scienceStudent.getChemistry(); //OK scienceStudent.getPhysics(); //OK
9
Downcasting – Potential Danger
Watch carefully the following case – Student student = new ScienceStudent("Rifat", 84, 92); BiologyStudentbiologyStudent = (BiologyStudent) student; It will throw ClassCastException!! Here ‘student’ “IS-A” ‘SceienceStudent’ but not a ‘BiologyStudent’. So the casting fails.
10
Operator instanceof and Downcasting
instanceof can be used to check the class of the object that a reference is pointing at run-time It returns a boolean value based on the “IS-A” relationship between an object (not the reference) and a class name Let, class A { }, class B extends A { }, class C extends A { } A o1 = new A(); A o2 = new B(); A o3 = new C(); Now, (o1 instanceof A), returns true (o2 instanceof A), returns true (o3 instanceof A), returns true (o3 instanceof C), returns true (o1 instanceof B), returns false (o2 instanceof C), returns false (o3 instanceof Object), returns true
11
Operator instanceof and Downcasting (const.)
Downcasting in Java but must be used with caution Invalid downcasting will throw “ClassCastException” It is an unchecked exception Let, class A { }, class B extends A { }, class C extends A { } A o1 = new A(); A o2 = new B(); A o3 = new C(); Now, B b1 = (B)o2; // no problem B b2 = (B)o3; // problem, ClassCastException C c1 = (C)o1; // problem, ClassCastException Should use the instanceof operator to see whether a downcasting will succeed or not, and prevent “ClassCastException” from occurring C c2; If(o3 instanceof C) c2 = (C)o3; else c2 = null;
12
Safe Downcasting with instanceof
Student student = new ScienceStudent("Rifat", 84, 92); BiologyStudentbiologyStudent= null; if (student instanceofBiologyStudent) { biologyStudent= (BiologyStudent) student; }
13
Why Called Run-Time? As the decision of which method to call is taken at run-time (by the JVM, not by the compiler) it is called run-time polymorphism. It is also called late binding or dynamic binding.
14
Compile-Time Polymorphism
Method overloading is an example of compile-time polymorphism as the compiler is able to decide which function to call during compile-time based on method’s argument information. It is called early binding or static binding too. The JVM does not have to do any checking while invoking a statically bound method.
15
Object All classes in Java inherit directly or indirectly from the Object class. What will be the output of the following code. MyClassobj= newMyClass(); System.out.println(obj); String s1 = “Hello ” + obj; Is it even right? Interestingly it is correct.
16
The “toString” method Gives a textual representation of every object
By default returns the package name and class name of the object followed by the character and the hash code value (obtained by calling the “hashCode” method) of the object Subclasses can override this method to return a custom String representation of the object Java automatically calls the “toString” method of an object when an object is used in such a place where a “String” is expected
17
toString (cont.) Let, MyClassobj = new MyClass();
The following two lines are equivalent System.out.println(obj.toString()); System.out.println(obj); Also, the following two lines are equivalent String s1 = “Hello ” + obj.toString(); String s1 = “Hello ” + obj;
18
Let’s Try!! Override the toString() method in previous session’s Student classes. package student; public class StudentToStringTest { public static void main(String[] args) { Student student = new Student("Fahad"); ScienceStudentscienceStudent = new ScienceStudent("Rifat", 84, 92); CommerceStudentcommerceStudent = new CommerceStudent("Ovi", 94, 96); BiologyStudentbiologyStudent = new BiologyStudent("Tanvir", 100, 105, 79); ComputerStudentcomputerStudent = new ComputerStudent("Fahim", 100, 105, 89); System.out.println(student); System.out.println(scienceStudent); System.out.println(commerceStudent); System.out.println(biologyStudent); System.out.println(computerStudent); } Output: [Name: Fahad] [Name: Rifat, Physics: 84, Chemistry: 92] [Name: Ovi, Accounting: 96, Economics: 94] [Name: Tanvir, Physics: 100, Chemistry: 105, Biology: 79] [Name: Fahim, Physics: 100, Chemistry: 105, Computer: 89]
19
Abstract Classes and Methods
Abstract Methods Does not have any body Must be declared as abstract Abstract Classes Contains one or more abstract methods Can also contain one or more concrete (non-abstract) methods Cannot be instantiated No object of such classes can be created Can declare references of such classes
20
Example: Employee package employee; public abstract class Employee { protected String name; public Employee(String name) { this.name = name; } public String getName() { return name; public void setName(String name) { public abstract double getSalary();
21
Abstract Classes and Methods (contd.)
Why use abstract classes? To create a general framework that can be overridden by subclasses To ensure that the subclass surely has some methods implemented inside them If a subclass of an abstract class fails to override an abstract method present in the superclass, the subclass also becomes abstract We can use an abstract superclass reference to point to a concrete subclass object and achieve run-time polymorphism
22
Abstract Methods and Abstract Classes
Sometimes a superclass method does not do any useful work. But the method must be present so that subclasses can override it and achieve run-time polymorphism. In that case we can declare the method as “abstract” and omit its body. public abstract void draw(); // In class Shape When we omit the body of a method we must declare it as “abstract”, otherwise the compiler will flag an error.
23
Abstract Methods and Abstract Classes (contd.)
If a class contains at least one abstract method, the class must be declared “abstract” also. Otherwise the compiler will flag an error. public abstract class Shape { } As an abstract class has one or more incomplete method(s), we cannot create/instantiate any objects of an abstract class.
24
Abstract Methods and Abstract Classes (contd.)
When a new class inherits from a abstract class, it must override all the abstract methods. Otherwise the subclass becomes an abstract class and must be declared as “abstract”. So, abstract methods are generally included to force subclasses to override the method with their specific versions.
25
Abstract Methods and Abstract Classes (contd.)
A class that has no abstract method is called a “concrete class”. We can create objects of concrete classes only. An abstract class can also contain non-abstract methods (called concrete methods).
26
Let’s Try!! Extend provided Employee class. Create two subclasses. One is PartTimeEmployee another is FullTimeEmployee. PartTimeEmployee have 2 extra fields. Hours and PerHour payment. Salary is calculated just multiplying hours and perHourPayment. Salary = hours * perHourPayment; FullTimeEmployee have 2 extra fields. BasicSalary and JobDuration in year. Salary is calculated based on BasicSalary and Total increment over all of the years. For simplicity in each year increment is 50% of the basic salary. So the complete formula is Salary = Basic + Basic * 0.5 * JobDuration;
27
Output public class EmployeeTest { public static void main(String[] args) { Employee employee1 = new FullTimeEmployee("A", 30000, 10); System.out.println(employee1); Employee employee2 = new PartTimeEmployee("B", 20, 1000); System.out.println(employee2); } Output: [Employee Name: A, Basic Salary: , Job Duration: 10, Total Salary: ] [Employee Name: B, Per Hour: , Hours: 20, Total Salary: ]
28
Interfaces When all the methods of a class are abstract and we do not want any concrete method in that class, we can declare the class as an “Interface”. An “Interface” is similar to an abstract class but cannot have any concrete methods. All the methods of an “Interface” must be abstract and declared as “abstract”. Otherwise the compiler will flag an error. While inheriting a new class from an interface, we have to use the keyword “implements” instead of “extends”. That means we “extend” a class (abstract or concrete) but we “implement” an interface.
29
Interfaces (contd.) Forgetting to override any method present in an interface will make the subclass an abstract class and that subclass must be declared as “abstract”. The “IS A” relationship holds with interfaces also. Interfaces are mainly used to ensure that subclasses implementing an interface will surely provide some methods of specific signatures. Otherwise those classes will become “abstract” and cannot be instantiated. This feature is heavily used in GUI programming, event handling and in many other parts of Java programming.
30
Interfaces (contd.) Interfaces can be used as superinterfaces to create subinterfaces. public interface BaseInterface { } public interface DerivedInterface extends BaseInterface { } Note that in this case, “extends” is used instead of “implements”. A subclass or subinterface can implement multiple interfaces. public class Line extends Shape implements SomeInterface { } public class SomeClassimplements SomeInterface, SomeOtherInterface { }
31
final Methods and Classes
Cannot be overridden in subclasses private methods are implicitly final static methods are implicitly final Uses static binding final class Cannot act as a superclass Cannot be further inherited by any class All methods in a final class are implicitly final Example: String, Math Attempting to extend from a final class or overriding a final method produces compiler error
32
Arrays A group of variables containing values that all have the same type Arrays are fixed-length entities In Java, arrays are objects, so they are considered reference types But the elements of an array can be either primitive types or reference types (including arrays)
33
Arrays (contd.) We access the element of an array using the following syntax nameOfArray [ index ] Here, “index” must be a nonnegative integer “index” can be int, byte, short or char but not long In Java, every array knows its own length. The length information is maintained in a public final int member variable called length.
34
Declaring and Creating Arrays
int c[ ] = new int [12]; Here, ‘c’ is a reference to an integer array ‘c’ is now pointing to an array object holding 12 integers Like other objects arrays are created using “new” and are created in the heap “int c[ ]” represents both the data type and the variable name. Placing number here is a syntax error. int c[12]; // syntax error/compiler error
35
Declaring and Creating Arrays (contd.)
int[ ] c = new int [12]; Here, the data type is more evident i.e. “int[ ]” But does the same work as int c[ ] = new int [12]; Is there any difference between the above two approaches? Yes. See the next slide.
36
Declaring and Creating Arrays (contd.)
int c[ ], x; Here, ‘c’ is a reference to an integer array ‘x’ is just a normal integer variable int[ ] c, x; Here, ‘c’ is a reference to an integer array (same as above) But, now ‘x’ is also a reference to an integer array
37
Using an Array Initializer
We can also use an array initializer to create an array int n[ ] = {10, 20, 30, 40, 50}; The length of the above array is 5 n[0] is initialized to 10, n[1] is initialized to 20, and so on The compiler automatically performs a “new” operation taking the count information from the list and initializes the elements properly.
38
Arrays of Primitive Types
When created by “new”, all the elements are initialized with default values byte, short, char, int, long, float and double are initialized to zero boolean is initialized to false This happens for both member arrays and local arrays
39
Arrays of Reference Types
String str[ ] = new String[3]; Only 3 String references are created Those references are initialized to “null” by default Both for member arrays and local arrays Need to explicitly create and assign actual String objects in the above three positions. str[0] = new String(“Hello”); str[1] = “World”; str[2] = “I” + “ Like” + “ Java”;
40
Passing Arrays to Methods
double temperature[ ] = new double[24]; modifyArray( temperature ); Here, “modifyArray” is declared as void modifyArray( double d[ ] ) Changes made to the elements of ‘d’ inside “modifyArray” is visible and reflected in the original “temperature” array. But inside “modifyArray” if we create a new array using “new” and assign it to ‘d’ then ‘d’ will point to the newly created array and changing its elements will have no effect on “temperature” (see next slide).
41
Passing Arrays to Methods (contd.)
So, we can say that while passing array to methods, changing the elements is visible, but changing the array reference itself is not visible. void modifyArray( double d[ ] ) { d[0] = 1.1; // visible to the caller … } d = new double [ 10 ]; d[0] = 1.1; // not visible to the caller
42
Multidimensional Arrays
Can be termed as array of arrays. int b[ ][ ] = new int[3][4]; Length of first dimension = 3 b.length equals 3 Length of second dimension = 4 b[0].length equals 4 int[ ][ ] b = new int[3][4]; Here, the data type is more evident i.e. “int[ ][ ]”
43
Multidimensional Arrays (contd.)
int b[ ][ ] = { { 1, 2, 3 }, { 4, 5, 6 } }; b.length equals 2 b[0].length and b[1].length equals 3 All these examples represent rectangular two dimensional arrays where every row has same number of columns. Java also supports jagged array where rows can have different number of columns (see next slide).
44
Multidimensional Arrays (contd.)
Example - 1 int b[ ][ ]; b = new int[ 2 ][ ]; b[ 0 ] = new int[ 2 ]; b[ 1 ] = new int[ 3 ]; b[0][2] = 7; // will throw an exception Example – 2 int b[ ][ ] = { { 1, 2 }, { 3, 4, 5 } }; b[0][2] = 8; // will throw an exception In both cases b.length equals 2 b[0].length equals 2 b[1].length equals 3 Array ‘b’ Col 0 Col 1 Col 2 Row 0 Row 1 b[0][2] does not exist!!
45
Using Command-Line Arguments
java MyClass arg1arg2 … argN Words after the class name are treated as command-line arguments by “java” “java” creates a separate String object containing each command-line argument, places them in a String array and supplies that array to “main” That’s why we have to have a String array parameter (String args[ ]) in “main”. We do not need a “argc” type parameter (for parameter counting) as we can easily use “args.length” to determine the number of parameters supplied.
46
Using Command-Line Arguments (contd.)
public class MyClass { public static void main ( String args[ ] ) System.out.println( args.length ); for( int i = 0; i < args.length; i++) System.out.println( args[i] ); } Sample Execution – 1 java MyClass Hello World Output: 2 Hello World Sample Execution – 2 java MyClass Hello 2 you 3 you
47
Exception Handling Say we have an array of size 3. Like
String str[] = new String[3]; But we accessed str[4]; then java will throw an exception nameArrayIndexOutOfBoundsException How to handle those?
48
try { } catch try { String str[] = new String[3]; str[4] = "123"; //will throw exception. System.out.println("This line won't be executed"); System.out.println("This line too"); int b = 100; System.out.println("Value of b: " + b + " but this won't be executed too"); } catch (ArrayIndexOutOfBoundsExceptionaioobe) { System.err.println("Improper access."); }
49
Exception-Handling Overview
Enables programmers to remove error-handling code from the “main line” of the program’s execution Improves program clarity Enhances modifiability Java forces the programmer to be prepared for certain types of problems so that sudden occurrence of such problems do not cause significant damage.
50
Exception-Handling Overview (contd.)
If a single-threaded program does not handle an exception, then it will be terminated immediately. If a multi-threaded program does not handle an exception, then it may not be terminated, but may show unusual behaviors. So, it is better to be prepared for different types of exceptions.
51
Syntax A single “try” block may be followed by zero or multiple “catch” blocks. If no “catch” block is provided, then a “finally” block must be provided for a “try” block. If no exception is thrown in the “try” block, then all the “catch” blocks are skipped and execution resumes after the last “catch” block. If an exception is thrown inside the “try” block, then execution immediately leaves the “try” block and Java searches for an appropriate “catch” handler capable of handling the exception from top to bottom. The first matching “catch” block is executed. All other “catch” blocks at the same level are skipped. The necessary information about the exception is wrapped inside an exception object and supplied to the corresponding “catch” handler. After all, Java does not do anything without objects. try { // statements that may throw exceptions } catch(ExceptionType1 refName) // statements to process ExceptionType1 catch(ExceptionType2 refName) // statements to process ExceptionType2 … catch(ExceptionTypeNrefName) // statements to process ExceptionTypeN
52
Some Common Exceptions
Exception classes in the Java API ArrayIndexOutOfBoundsException NullPointerException ClassCastException ArithmeticException InputMismatchException FileNotFoundException InterruptedException IOException (package java.io) Exception (package java.lang) And many more. You can also develop your own exception classes.
53
Assignment!! Create a base interface name Shape.
Which has a abstract method draw(); Create the a hierarchy of classes. For detail take a look at the course website.
54
Shape Hierarchy!! Shape Line Triangle Rectangle Circle Cylinder Cone
Oval
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.