Java Unit III
Java Unit III
30 Marks
End Sem (Theory):
304185 (C): Fundamentals of Java Programming 70 Marks
(Elective - I)
TE (E&TC) 2019 Course
2
Data Structures: CO-PO Mapping
Course Blooms Taxonomy After successful completion of the course Mapping with
PO MAPPING
Outcome Level students will be able to Syllabus Unit
TEXT BOOKS
1. E Balagurusamy, “Programming with JAVA”, Tata McGraw Hill, 6th Edition.
2. Herbert Schildt, “Java: The complete reference”, Tata McGraw Hill, 7th Edition.
REFERENCE BOOKS
1. T. Budd, “Understanding OOP with Java”, Pearson Education, 2nd Updated Edition.
2. Y. Daniel Liang (2010), “Introduction to Java programming”, Pearson Education, India, 7th Edition.
3. Cay Horstmann , “Core Java Volume 1”, Kindle, 11th Edition.
ADDITIONAL MATERIAL
4
OOP: Topic – Book – Pages Mapping
Reference / text book
Sr. No. Topic
with page no.
UNIT IV:
1 Abstract Methods and classes T2: 182-184
2 Strings,
One dimensional and two dimensional arrays T2:413-439
6
Abstract Classes and
Methods
The abstract keyword is a non-access modifier, used for classes and methods:
Abstract class: is a restricted class that cannot be used to create objects (to
access it, it must be inherited from another class).
Abstract method: can only be used in an abstract class, and it does not have a
body. The body is provided by the subclass (inherited from).
An abstract class can have both abstract and regular methods
7
Abstract Classes
An abstract class is a class that is declared abstract—it may or may not include
abstract methods. Abstract classes cannot be instantiated, but they can be
subclassed.
If a class includes abstract methods, then the class itself must be declared
abstract, as in:
public abstract class GraphicObject {
// declare fields
// declare nonabstract methods
abstract void draw();
}
8
Abstract class
To access the abstract class, it must be inherited from another class.
When an abstract class is subclassed, the subclass usually provides
implementations for all of the abstract methods in its parent class. However, if it
does not, then the subclass must also be declared abstract.
9
abstract class A {
void callmetoo() {
class B extends A {
Although abstract classes cannot be used to instantiate
objects, they can be used to create object references,
void callme() {
because Java’s approach to run-time polymorphism is
[Link]("B's implementation of callme."); } implemented through the use of superclass references.
}
Thus, it must be possible to create a reference to
an abstract class so that it can be used to point to a
class AbstractDemo {
subclass object.
public static void main(String args[]) {
B b = new B();
[Link]();
[Link](); }
10
Rules for Abstract Class
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors and static methods also.
It can have final methods which will force the subclass not to
change the body of the method.
11
Abstract Methods
A method without body (no implementation) is known as abstract method.
A method must always be declared in an abstract class
Syntax : public abstract int myMethod(int n1, int n2);
this has no body.
12
Rules of Abstract Method
1. Abstract methods don’t have body, they just have method signature
as shown above.
2. If a class has an abstract method it should be declared abstract, the
vice versa is not true, which means an abstract class doesn’t need to
have an abstract method compulsory.
3. If a regular class extends an abstract class, then the class must have
to implement all the abstract methods of abstract parent class or it has
to be declared abstract as well.
13
abstract class Figure { double dim1; class Triangle extends Figure { class AbstractAreas {
Figure(double a, double b) { dim1 = a; super(a, b); // Figure f = new Figure(10, 10); // illegal now
// area is now an abstract method double area() { Figure figref; // this is OK, no object is created
} }
double area() {
14
Strings
String is non primitive Data Type
String is a class.
Object is the parent class of all classes in Java, So parent class of string is object.
Strings in Java are Objects that are backed internally by a char array
Since arrays are immutable(cannot grow), Strings are immutable as well
Syntax:
<String_Type> <string_variable> = "<sequence_of_string>";
It implements' CharSequence, Serializable and Comparable
15
Creating a String
1. String literal
String str = “Java";
This allows JVM to optimize the initialization of String literal.
2. Using new keyword
The string can also be declared using new operator i.e. dynamically allocated
String str = new String(“Java");
It is preferred to use String literals as it allows JVM to optimize memory
allocation.
16
String Methods
1. int length(): Returns the number of characters in the String.
2. Char charAt(int i): Returns the character at ith index
3. String substring (int i): Return the substring from the ith index character to end
4. String substring (int i, int j): Returns the substring from i to j-1 index.
5. boolean equals( Object otherObj): Compares this string to the specified object
6. boolean equalsIgnoreCase (String anotherString): Compares string to another string, ignoring case
considerations.
7. int compareTo( String anotherString): Compares two string lexicographically.
int out = [Link](s2); // where s1 ans s2 are strings to be compared This returns difference s1-s2.
If : out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
17
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 18
CTRONICS AND TELECOMMUNICATION
19
20
21
22
23
24
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 46
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 47
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 48
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 49
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 50
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 51
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 52
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 53
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 68
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 69
CTRONICS AND TELECOMMUNICATION
Arrays
One - dimensional array
Declaring the array
A list of items that can be given one variable name using only one subscript and such a
variable is called one scripted variable or one dimensional array.
Form1 : type arrayname[];
Form2: type [] arrayname;
float avg[];
int[] counter;
float[] marks;
Note : we don’t enter size of the array in declaration.
Creation of array
After we declare the array we need to create it in the memory
Java allows us to create arrays using new operator only
Syntax : arrayname=new type[size];
Ex : number = new int[5];
avg=new float[10];
It is possible to combine declaration and creation
int number=new int[5];
Initialization of arrays
Syntax : arrayname[subscript]=value;
Ex :
number[0]=10;
number[1]=20;
Note :java creates the starting index with 0 and end with one less than the size of the
array.
type arrayname={list of values};
Ex: int num[]={10,20,30,40};
int a[]={1,2,3};
int b[];
b=a;
Assigning one arrays to another.
class demo12
public static void{ main(String[] args) {int[] a=new int[5];
a[0]=211;a[1]=10;a[2]=12;
a[3]=21;a[4]=100;
int[] b=new int[5]; b=a;
[Link]("array of b is:"+b);}}
Array length
In java , all arrays store the allocated size in a variable named length.
We can obtain the length of array ‘a’ by [Link].
Ex : int arraylength=[Link]
One dimensional Array
Syntax:
dataType[] arrayName;
// declare an array
double[] data;
// allocate memory
data = new double[10]
92
Multi dimensional Arrays
Syntax:
data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name =
new data_type[size1][size2]….[sizeN];
where:
•data_type: Type of data to be stored in the array. For example: int, char, etc.
•dimension: The dimension of the array created.
•For example: 1D, 2D, etc.
•array_name: Name of the array
•size1, size2, …, sizeN: Sizes of the dimensions respectively.
93
Two – dimensional Array (2D-
Array)
class Array1 {
public static void main(String[] args)
{
int[][] arr = { { 1, 2 }, { 3, 4 } };
Output:
arr[0][0] = 1
for (int i = 0; i < 2; i++) arr[0][1] = 2
arr[1][0] = 3
for (int j = 0; j < 2; j++) arr[1][1] = 4
[Link]("arr[" + i + "][" + j + "] = ”+ arr[i][j]);
}
}
94
Wrapper Classes in Java
95
99
March 9, 2026 100
101
March 9, 2026 102
Wrapper Classes in Java
a class whose object wraps or contains primitive data types
Autoboxing: Automatic conversion of primitive types to the object of their
corresponding wrapper classes is known as autoboxing.
For example – conversion of int to Integer, long to Long, double to Double etc.
Unboxing: It is just the reverse process of autoboxing. Automatically
converting an object of a wrapper class to its corresponding primitive type is
known as unboxing
For example – conversion of Integer to int, Long to long, Double to double, etc.
103
Need of Wrapper Classes
They convert primitive data types into objects. Objects are needed if we wish to
modify the arguments passed into a method (because primitive types are passed
by value).
The classes in [Link] package handles only objects and hence wrapper classes
help in this case also.
Data structures in the Collection framework, such as ArrayList and Vector, store
only objects (reference types) and not primitive types.
An object is needed to support synchronization in multithreading.
104
105
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 106
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 107
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 108
CTRONICS AND TELECOMMUNICATION
package FJP_Lecture;
[Link](num2);
109
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 110
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 111
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 112
CTRONICS AND TELECOMMUNICATION
Example of Autoboxing
class AutoBox2 {
// Take an Integer parameter and return an int value; Output:
113
Example of Unboxing
class AutoBox4 {
public static void main(String args[]) {
Output:
Integer iOb = 100;
Double dOb = 98.6; dOb after expression: 198.6
both the Double object dOb and the Integer object iOb participated in the
addition, and the result was reboxed and stored in dOb.
114
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 115
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 116
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 117
CTRONICS AND TELECOMMUNICATION
Enumerated Types
An enumerated type is a type whose legal values consist of a fixed set of constants
enum Color
{ RED, GREEN, BLUE; }
Output :
public class Test
RED
{ // Driver method
public static void main(String[] args)
{ Color c1 = [Link];
[Link](c1);
}
}
118
Properties of enumerated
Types
Printed values are informative.
They exist in their own namespace.
The set of constants is not required to stay fixed for all time.
You can switch on an enumeration constant.
They have a static values method that returns an array containing all of the values of the enum
type in the order they are declared.
You can provide methods and fields, implement interfaces, and more.
They provide implementations of all the Object methods.
They are Comparable and Serializable, and the serial form is designed to withstand changes in
the enum type.
119
• Command line argument means input given by the user at the run time of program, means
user pass some values at the run time.
• Command line arguments are objects of String class.
• Command line argument is used for customization of main method.
//args is reference variable which refer to
String type array
Using Eclipse
1. Run as-Run configuration
2. Select program
3. Select argument tab
4. Give argument
5. Apply Run
Example
public class Test
{
public static void main( String[] args )
{
Int n=[Link](args[0]);
[Link](“The square of +n+ is”:+(n*n));
}
}
Output:
RUN----Java Test 4
The square of 4 is:16
RUN----Java Test 5
The square of 5 is:25
Command line arguments
The java command-line argument is an argument i.e. passed at the time of running the java
program.
129
Inheritance in Java
Important terminology:
Super Class: The class whose features are inherited is known as superclass(or a
base class or a parent class).
Sub Class: The class that inherits the other class is known as a subclass(or a
derived class, extended class, or child class). The subclass can add its own fields
and methods in addition to the superclass fields and methods.
Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some of the
code that we want, we can derive our new class from the existing class. By doing
this, we are reusing the fields and methods of the existing class.
132
Types of Inheritance in Java
1. Single Inheritance: subclasses inherit the
features of one superclass.
136
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 137
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 138
CTRONICS AND TELECOMMUNICATION
Example of Single Inheritance
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
} 139
Output:
Programmer salary is:40000.0
Bonus of programmer is:10000
Thus, super( ) always refers to the superclass immediately above the calling class.
Also, super( ) must always be the first statement executed inside a subclass
constructor.
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 154
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 155
CTRONICS AND TELECOMMUNICATION
A subclass can call a constructor defined by its superclass by use of the following form of super:
super(arg-list);
Here, arg-list specifies any arguments needed by the constructor in the superclass.
super( ) must always be the first statement executed inside a subclass’
constructor.
vol = [Link]();
[Link]("Volume of mybox2 is " + vol); [Link]("Weight of
mybox2 is " +[Link]);
[Link]();
vol = [Link]();
[Link]("Volume of mybox3 is " + vol); [Link]("Weight of
mybox3 is " +[Link]);
[Link]();
vol = [Link]();
[Link]("Volume of myclone is " + vol); [Link]("Weight of myclone
is " +[Link]);
[Link]();
vol = [Link]();
[Link]("Volume of mycube is " + vol);
[Link]("Weight of mycube is " +[Link]);
[Link]();
}
}
This program generates the following output:
Notice that super( ) is passed an object of type BoxWeight—not of type Box. This
still invokes the constructor Box(Box ob).
A Second Use for super
The second form of super acts somewhat like this, except that it always refers to the
superclass of the subclass in which it is used. This usage has the following general form:
[Link]
This second form of super is most applicable to situations in which member names of a
subclass hide members by the same name in the superclass. Consider this simple class
hierarchy:
// Using super to overcome name hiding.
class A {
int i;
}
// Create a subclass by extending class A.
class B extends A {
int i; // this i hides the i in A
B(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show()
[Link]("i in superclass: " + super.i);
[Link]("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
[Link]()
}
}
This program displays the following:
i in superclass: 1
i in subclass: 2
Although the instance variable i in B hides the i in A, super allows access to the i
defined in the superclass.
As you will see, super can also be used to call methods that are hidden by a subclass.
169
170
171
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 172
CTRONICS AND TELECOMMUNICATION
When Constructors Are Called
(Constructor in Derived Class)
When a class hierarchy is created, in what order are the constructors for the classes
that make up the hierarchy called?
For example, given a subclass called B and a superclass called A, is A’s constructor
called before B’s, or vice versa? The answer is that in a class hierarchy, constructors
are called in order of derivation, from superclass to subclass.
Further, since super( ) must be the first statement executed in a subclass’ constructor,
this order is the same whether or not super( ) is used.
177
Constructors in derived class
When both the derived and base class contains constructors, the base constructor is
executed first and then the constructor in the derived class is executed.
In case of multiple inheritance, the base class is constructed in the same order in
which they appear in the declaration of the derived class. Similarly, in a multilevel
inheritance, the constructor will be executed in the order of inheritance.
The derived class takes the responsibility of supplying the initial values to its base
class.
The constructor of the derived class receives the entire list of required values as its
argument and passes them on to the base constructor in the order in which they are
declared in the derived class. A base class constructor is called and executed before
executing the statements in the body of the derived class.
178
When Constructors Are
Executed
in a class hierarchy, constructors complete their execution in order
of derivation, from superclass to subclass.
since super( ) must be the first statement executed in a subclass’
constructor, this order is the same whether or not super( ) is used.
If super( ) is not used, then the default or parameter less
constructor of each superclass will be executed.
179
class A { class C extends B {
A() { C() {
[Link]("Inside A's constructor."); [Link]("Inside C's constructor.");
} }
} }
// Create a subclass by extending class A. class CallingCons {
class B extends A { public static void main(String args[]) {
B() { C c = new C();
[Link]("Inside B's constructor."); }
} }
} Output:
Inside A's constructor
Inside B's constructor
Inside C's constructor
180
Constructors in derived class
a constructor of a derived class must also take care of the construction of the fields of the base class.
This can be done by inserting in the constructor of the derived class the call to a constructor of the base
class, using the special Java construct super().
The super() statement must appear as the first executable statement in the body of the constructor of the
derived class.
public class Student extends Person {
public Student(String n, String r, String f) {
super(n,r); // calls the constructor Person(String,String)
faculty = f;
}
...
}
181
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature as
a method in its superclass, then the method in the subclass is said to override the method
in the superclass.
The version of the method defined by the superclass will be hidden. Consider the following:
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 184
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 185
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 186
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 187
CTRONICS AND TELECOMMUNICATION
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a; j = b;
}
// display i and j
void show() {
[Link]("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
[Link]("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
[Link](); // this calls show() in B
}
}
The output produced by this program is shown here:
k: 3
When show( ) is invoked on an object of type B, the version of show( ) defined within
B is used. That is, the version of show( ) inside B overrides the version declared in A.
If you wish to access the superclass version of an overridden method, you can do so
by using super. For example, in this version of B, the superclass version of show( ) is
invoked within the subclass’ version. This allows all instance variables to be displayed.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
[Link](); // this calls A's show()
[Link]("k: " + k);
}
}
If you substitute this version of A into the previous program, you
will see the following output:
i and j: 1 2
k: 3
Here, [Link]( ) calls the superclass version of show( ).
Method overriding occurs only when the names and the type signatures of the two methods are
identical. If they are not, then the two methods are simply overloaded.
For example, consider this modified version of the preceding example:
// Methods with differing type signatures are overloaded – not overridden.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
[Link]("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// overload show()
void show(String msg) {
[Link](msg + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
[Link]("This is k: "); // this calls show() in B
[Link](); // this calls show() in A
}
}
The output produced by this program is shown here:
This is k: 3
i and j: 1 2
The version of show( ) in B takes a string parameter. This makes its type signature
different from the one in A, which takes no parameters.
Therefore, no overriding (or name hiding) takes place. Instead, the version of show( ) in B
simply overloads the version of show( ) in A.
Method overriding
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in Java.
Usage of Java Method Overriding
1. Method overriding is used to provide the specific implementation of a method
which is already provided by its superclass.
2. Method overriding is used for runtime polymorphism
3. Method overriding forms the basis for one of Java’s most powerful concepts:
dynamic method dispatch
195
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 196
CTRONICS AND TELECOMMUNICATION
Rules for Java Method
Overriding
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
197
Example of method
overriding
class Vehicle{
public static void main(String args[])
//defining a method {
Bike2 obj = new Bike2();//creating object
void run()
[Link]();//calling method
{[Link]("Vehicle is running"); } }
}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class Output:
Bike is running safely
void run()
{[Link]("Bike is running safely");}
198
199
Dynamic Method Dispatch
Dynamic method dispatch is the mechanism by which a call to an overridden method is
resolved at run time, rather than compile time.
When an overridden method is called through a superclass reference, Java determines which
version of that method to execute based upon the type of the object being referred to at the
time the call occurs.
Thus, this determination is made at run time. When different types of objects are referred to,
different versions of an overridden method will be called.
In other words, it is the type of the object being referred to (not the type of the reference
variable) that determines which version of an overridden method will be executed.
r = c; // r refers to a C object
[Link](); // calls C's version of callme
}
}
Subclasses B and C override callme( ) declared in A. Inside the main( ) method, objects of
type A, B, and C are declared. Also, a reference of type A, called r, is declared.
The program then in turn assigns a reference to each type of object to r and uses that
reference to invoke callme( ).
As the output shows, the version of callme( ) executed is determined by the type of object
being referred to at the time of the call. Had it been determined by the type of the reference
variable, r, you would see three calls to A’s callme( ) method.
Used correctly, the superclass provides all elements that a subclass can use directly.
It also defines those methods that the derived class must implement on its own. This allows
the subclass the flexibility to define its own methods, yet still enforces a consistent interface.
Dynamic, run-time polymorphism is one of the most powerful mechanisms that object
oriented design brings to bear on code reuse and robustness.
Applying Method Overriding
The following program creates a superclass called Figure that stores the dimensions of a
two-dimensional object.
It also defines a method called area( ) that computes the area of an object.
Each of these subclasses overrides area( ) so that it returns the area of a rectangle and a
triangle, respectively.
// Using run-time polymorphism. class Figure {
double dim1; double dim2;
Figure(double a, double b) { dim1 = a;
dim2 = b;
}
double area() {
[Link]("Area for Figure is undefined."); return 0;
}
}
class Rectangle extends Figure { Rectangle(double a, double b) {
super(a, b);
}
// override area for rectangle double area() {
[Link]("Inside Area for Rectangle."); return dim1 * dim2;
}
}
class Triangle extends Figure { Triangle(double a, double b) {
super(a, b);
}
// override area for right triangle double area() {
[Link]("Inside Area for Triangle.");
return dim1 * dim2 / 2;
}
}
class FindAreas {
public static void main(String args[]) { Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5); Triangle t = new Triangle(10, 8); Figure
figref;
figref = r;
[Link]("Area is " + [Link]());
figref = t;
[Link]("Area is " + [Link]());
figref = f;
[Link]("Area is " + [Link]());
}
}
The output from the program is shown here: Inside Area for
Rectangle.
Area is 45
Inside Area for Triangle. Area is 40
Area for Figure is undefined. Area is 0
Dynamic method dispatch
Dynamic method dispatch is the mechanism by which a call to an overridden
method is resolved at run time, rather than compile time.
When an overridden method is called by a reference, java determines which
version of that method to execute based on the type of object it refer to.
the type of object which it referred determines which version of overridden
method will be called.
214
Example of Dynamic method
dispatch
class A {
class Dispatch {
void callme() { public static void main(String args[]) {
A a = new A(); // object of type A
[Link]("Inside A's callme method"); }
B b = new B(); // object of type B Output:
} C c = new C(); // object of type C Inside A's callme method
class B extends A { // override callme()
A r; // obtain a reference of type A Inside B's callme method
r = a; // r refers to an A object Inside C's callme method
void callme() [Link](); // calls A's version of callme
{ [Link]("Inside B's callme method"); } r = b; // r refers to a B object
[Link](); // calls B's version of callme
} r = c; // r refers to a C object
class C extends A { [Link](); // calls C's version of callme
}
// override callme()
}
void callme() {
[Link]("Inside C's callme method");
} 215