0% found this document useful (0 votes)
9 views215 pages

Java Unit III

The document outlines the syllabus for the 'Fundamentals of JAVA Programming' course at Savitribai Phule Pune University, focusing on key topics such as methods, inheritance, and data structures in Java. It includes details on the teaching and examination scheme, course outcomes, and mapping with program outcomes. Additionally, it provides references to textbooks and additional materials for further learning.

Uploaded by

Riya Kamble
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views215 pages

Java Unit III

The document outlines the syllabus for the 'Fundamentals of JAVA Programming' course at Savitribai Phule Pune University, focusing on key topics such as methods, inheritance, and data structures in Java. It includes details on the teaching and examination scheme, course outcomes, and mapping with program outcomes. Additionally, it provides references to textbooks and additional materials for further learning.

Uploaded by

Riya Kamble
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

Savitribai Phule Pune University

Third Year of E & Tc Engineering (2019 Course)


304185 (C): Fundamentals of JAVA Programming (Elective - I)
Teaching Scheme: Credit Examination Scheme:
Theory: 03 hrs. / week 03In-Sem (Theory):

30 Marks
End Sem (Theory):
304185 (C): Fundamentals of Java Programming 70 Marks

(Elective - I)
TE (E&TC) 2019 Course

[Link] Atul Patil


Unit III
Methods & Inheritance in JAVA
(06 Hrs)
Abstract Methods and classes,
Strings ,
One dimensional and two dimensional arrays ,
wrapper classes,
enumerated types, Command line arguments
Inheritance: Inheritance in Java,
Creating Multilevel hierarchy,
Constructors in derived class,
Method overriding,
Dynamic method dispatch.

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

Program Outcomes (POs)


1. Engineering knowledge 1,2,3,5
2. Problem analysis
CO304185 Demonstrate the concepts [Link]/development
& of solutions
3 3 of complex problems
4. Conduct investigations
(C).3 Inheritance
MAPPING LEVEL JUSTIFICATION 5. Modern tool usage
CO3-PO1 Every Program is based on knowledge of 6. The engineer and society
3 mathematics, science and engineering 7. Environment and sustainability
fundamentals 8. Ethics
CO3-PO2 Designing and development of OOP features of 9. Individual and team work
3 Java for analysis of complex engineering problem.
10. Communication
CO3-PO3 Selection of proper OOP feature of Java is done 11. Project management and finance
3 based on given problem statement for formulating 12. Life-long learning
and analysing CEP.
CO3-PO5 Modern tools like Netbeans, Eclipse, etc. are used
3 for development of programs.
March 9, 2026 3
Books

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

1. NPTEL Course “Programming in Java”

Link of the Course: [Link]

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

3 wrapper classes, T2: 272-274


enumerated types, T2: 263-272
Command line arguments
4 Inheritance: Inheritance in Java,
Creating Multilevel hierarchy T2:161-174
T2:171-174

5 Constructors in derived class T2: 174-175


6 Method overriding,
Dynamic method dispatch T2: 175-181
T2: 178-181
5
Abstract Classes and Methods
• Data abstraction is the process of hiding certain details and showing
only essential information to the user.

• Abstraction can be achieved with either abstract classes or interfaces

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 {

abstract void callme();

// concrete methods are still allowed in abstract classes

void callmetoo() {

[Link]("This is a concrete method."); }

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 {

double dim2; Triangle(double a, double b) { public static void main(String args[]) {

Figure(double a, double b) { dim1 = a; super(a, b); // Figure f = new Figure(10, 10); // illegal now

dim2 = b; } Rectangle r = new Rectangle(9, 5);

} // override area for right triangle Triangle t = new Triangle(10, 8);

// area is now an abstract method double area() { Figure figref; // this is OK, no object is created

abstract double area(); [Link]("Inside Area for Triangle."); figref = r;

} return dim1 * dim2 / 2; [Link]("Area is " + [Link]());

class Rectangle extends Figure { } figref = t;

Rectangle(double a, double b) { super(a, b); } [Link]("Area is " + [Link]());

} }

// override area for rectangle }

double area() {

[Link]("Inside Area for Rectangle.");

return dim1 * dim2; }

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.

String is sequence of character (Array of Character)


char[]={‘s’ ‘a’ ‘r’ ‘i’ ‘k’ ‘a’}

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;

Ex: int num[];

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;

public class Wrap {

public static void main(String[] args) {


int num=5;
Integer num1=num; //autoboxing

int num2=num1; //auto-unboxing

[Link](num2);

String str ="12"; Output:


5
int num3 = [Link](str);
24
[Link](num3*2);
}

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:

static int m(Integer v) 100


{ return v ; // auto-unbox to int }
public static void main(String args[]) In the program, notice that m( ) specifies an Integer
parameter and returns an int result. Inside main( ), m( ) is
{ passed the value 100. Because m( ) is expecting an Integer,
Integer iOb = m(100); this value is automatically boxed. Then, m( ) returns the int
equivalent of its argument. This causes v to be auto-
[Link](iOb); unboxed. Next, this int value is assigned to iOb in main( ),
which causes the int return value to be autoboxed
}
}

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

dOb = dOb + iOb;


[Link]("dOb after expression: " + dOb);
}
}

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.

2. Multilevel Inheritance: In Multilevel


Inheritance, a derived class will be inheriting a base
class and as well as the derived class also act as the
base class to other class.
Types of Inheritance in Java
3. Hierarchical Inheritance: one class serves as a superclass
(base class) for more than one subclass.

4. Multiple Inheritance (Through Interfaces): In Multiple


inheritances, one class can have more than one superclass
and inherit features from all parent classes.
Types of Inheritance in Java
5. Hybrid Inheritance(Through Interfaces): It is a mix of two or more of the above types of
inheritance. Since java doesn’t support multiple inheritances with classes, hybrid inheritance is
also not possible with classes. In java, we can achieve hybrid inheritance only through Interfaces.

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

March 9, 2026 140


Creating a Multilevel Hierarchy
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 143
CTRONICS AND TELECOMMUNICATION
Creating Multilevel hierarchy public class Demo {
public static void main(String args[])
class A { {
void funcA() { C obj = new C();
[Link]("This is class A"); [Link]();
} } [Link]();
[Link]();
class B extends A {
}
void funcB() { }
[Link]("This is class B");
}
}
class C extends B {
void funcC() {
[Link]("This is class C");
}
} 144
Output
This is class A
This is class B
This is class C

March 9, 2026 145


March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 146
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 147
CTRONICS AND TELECOMMUNICATION
March 9, 2026 K.K. WAGH INSTITUTE OF ENGINEERING EDUCATION AND RESEARCH, NASHIK DEPARTMENT OF ELE 148
CTRONICS AND TELECOMMUNICATION
150
Using super to Call Superclass
Constructors
 When a subclass calls super( ), it is calling the constructor of its immediate
superclass.

 Thus, super( ) always refers to the superclass immediately above the calling class.

 This is true even in a multileveled hierarchy.

 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.

// BoxWeight now uses super to initialize its Box attributes.


class BoxWeight extends Box {
double weight; // weight of box
// initialize width, height, and depth using super()
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
}
// A complete implementation of BoxWeight.
class Box {
private double width;
private double height;
private double depth;
// construct clone of an object
Box(Box ob) { // pass object to constructor
width = [Link];
height = [Link];
depth = [Link];
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
// constructor used when cube is created Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
// BoxWeight now fully implements all constructors.
class BoxWeight extends Box {
double weight; // weight of box
// construct clone of an object
BoxWeight(BoxWeight ob) { // pass object to constructor
super(ob);
weight = [Link];
}
// constructor when all parameters are specified
BoxWeight(double w, double h, double d, double m) {
super(w, h, d); // call superclass constructor
weight = m;
}
// default constructor
BoxWeight() {
super();
weight = -1;
}
// constructor used when cube is created
BoxWeight(double len, double m) {
super(len);
weight = m;
}
}
class DemoSuper {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076);
BoxWeight mybox3 = new BoxWeight(); // default
BoxWeight mycube = new BoxWeight(3, 2);
BoxWeight myclone = new BoxWeight(mybox1);
double vol;
vol = [Link]();
[Link]("Volume of mybox1 is " + vol); [Link]("Weight of
mybox1 is " +[Link]);
[Link]();

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:

Volume of mybox1 is 3000.0


Weight of mybox1 is 34.3

Volume of mybox2 is 24.0


Weight of mybox2 is 0.076

Volume of mybox3 is -1.0


Weight of mybox3 is -1.0

Volume of myclone is 3000.0


Weight of myclone is 34.3

Volume of mycube is 27.0


Weight of mycube is 2.0
 Pay special attention to this constructor in BoxWeight( ):

// construct clone of an object


BoxWeight(BoxWeight ob) { // pass object to constructor super(ob);
weight = [Link];
}

 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]

 Here, member can be either a method or an instance variable.

 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.

 If super( ) is not used, then the default or parameterless constructor of each


superclass will be executed.
// Create a super class.
class CallingCons {
class A {
public static void main(String args[]) {
A() {
C c = new C();
[Link]("Inside A's constructor.");
}
} }
}
// Create a subclass by extending class A.
class B extends A {
B() {
[Link]("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
[Link]("Inside C's constructor.");
}
}
The output from this program is shown here:

Inside A’s constructor


Inside B’s constructor
Inside C’s constructor

The constructors are called in order of derivation.


Constructors in derived class
A constructor plays a vital role in initializing an object.
As long as a base class constructor does not take any arguments, the derived
class need not have a constructor function.
If a base class contains a constructor with one or more arguments, then it is
mandatory for the derived class to have a constructor and pass the arguments
to the base class constructor.
While applying inheritance, we usually create objects using derived class.
Thus, it makes sense for the derived class to pass arguments to the base class
constructor.

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.

 When an overridden method is called from within a subclass, it will


always refer to the version of that method defined by the subclass.

 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.

 Therefore, if a superclass contains a method that is overridden by a subclass, then when


different types of objects are referred to through a superclass reference variable, different
versions of the method are executed.
 Therefore, if a superclass contains a method that is overridden by a subclass, then when
different types of objects are referred to through a superclass reference variable, different
versions of the method are executed.

// Dynamic Method Dispatch


class A {
void callme() {
[Link]("Inside A's callme method");
}
}
class B extends A {
// override callme()
void callme() {
[Link]("Inside B's callme method");
}
}
class C extends A {
// override callme()
void callme() {
[Link]("Inside C's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
r = a; // r refers to an A object
[Link](); // calls A's version of callme
r = b; // r refers to a B object
[Link](); // calls B's version of callme

r = c; // r refers to a C object
[Link](); // calls C's version of callme
}
}

The output from the program is shown here:

Inside A’s callme method


Inside B’s callme method
Inside C’s callme method
 This program creates one superclass called A and two subclasses of it, called B and C.

 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.

 Overridden methods in Java are similar to virtual functions in C++/C# languages.


Why Overridden Methods?
 Overridden methods allow Java to support run-time polymorphism.
 Polymorphism is essential to object-oriented programming for one reason: it allows a
general class to specify methods that will be common to all of its derivatives, while allowing
subclasses to define the specific implementation of some or all of those methods.
 Overridden methods are another way that Java implements the “one
interface, multiple methods” aspect of polymorphism.

 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.

 The program derives two subclasses from Figure.

 The first is Rectangle and the second is Triangle.

 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

You might also like