0% found this document useful (0 votes)
3 views

U3A Java_Inheritance

The document provides an overview of inheritance in Java, explaining how a subclass can inherit features from a superclass, enhancing code reusability and productivity. It details the use of the 'extends' keyword, the role of the 'super' keyword, and includes examples demonstrating simple and complex inheritance structures. Additionally, it discusses access modifiers and their implications on member visibility in inheritance scenarios.

Uploaded by

gadhiyadaksh26
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

U3A Java_Inheritance

The document provides an overview of inheritance in Java, explaining how a subclass can inherit features from a superclass, enhancing code reusability and productivity. It details the use of the 'extends' keyword, the role of the 'super' keyword, and includes examples demonstrating simple and complex inheritance structures. Additionally, it discusses access modifiers and their implications on member visibility in inheritance scenarios.

Uploaded by

gadhiyadaksh26
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 73

Inheritance

in
JAVA
SUBJECT: 4341602 Object Oriented Programming with Java
SEM: IV (Diploma Information Technology)

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Introduction
 It is possible to acquire all the members of a class and use them
in another class by relating the objects of the two classes. This is
possible by using inheritance concept.
 When a class is written by programmer and another
programmer wants the same features(members) in his class
also, then the other programmer can go for inheritance.
 This is done by deriving the new class from the existing class.
 Deriving new classes from existing classes such that the new
classes acquire all the features of existing classes is called
inheritance.

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Introduction
 Using inheritance, we can create a general class
Superclass

Feature A that defines traits common to a set of related


items.
Feature B
 This class can then be inherited by other, more
Feature C specific classes, each adding those things that
are unique to it.
 In the terminology of Java, a class that is
Feature A
Defined in
inherited is called a superclass. The class that
Feature B superclass does the inheriting is called a subclass.
but accessible
from subclass
 Therefore, a subclass is a specialized version of a
Feature C
superclass. It inherits all of the members defined
Feature D
New feature
defined in
by the superclass and adds its own, unique
subclass elements.
Subclass
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Teacher class
class Teacher{ void setName(String name){
int id; this.name = name;
String name; }
String address; String getName(){
return name;
void setId(int id){ }
this.id = id; void setAddr(String address){
} this.address = address;
int getId(){ }
return id; String getAddr(){
} return address;
}
}

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Student class-1
class Student { class studCheck{
int id; public static void main(String args[]){
String name; Student s = new Student();
String address; s.setId(101);
int marks; s.setName("Ramesh Patel");
void setId(int id){ s.setAddr("12, Park Avenue");
this.id = id;} s.setMark(39);
int getId(){ return id;} System.out.println("ID ="+s.getId());
void setName(String name){ System.out.println("Name ="+s.getName());
this.name = name; } System.out.println("Address ="+s.getAddr());
String getName(){ return name; System.out.println("Marks ="+s.getMark());
} }
void setAddr(String address){ }
this.address = address; }
String getAddr(){ return address;
}
void setMark(int marks){
this.marks = marks; }
int getMark(){ return marks;}
}
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Student class-2
class Teacher{ class Student extends Teacher{
int id; int marks;
String name; void setMark(int marks){
String address; this.marks = marks;
void setId(int id){ }
this.id = id; int getMark(){
} return marks;
int getId(){ return id;} }
}
void setName(String name){ class StudUse{
this.name = name; public static void main(String args[]){
} Student s = new Student();
String getName(){ return name;} s.setId(1002);
void setAddr(String address){ s.setName("Naresh Pathak");
this.address = address; s.setAddr("102, Palika Bhavan");
s.setMark(45);
}
System.out.println("ID ="+s.getId());
String getAddr(){ return address;} System.out.println("Name ="+s.getName());
} System.out.println("Address ="+s.getAddr());
System.out.println("Marks ="+s.getMark());
}
}
Prac-18_A
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Super-class Teacher and Sub-class Student
 We can visualize the super-class Teacher and sub-class Student as below:
 Observe the Student class has inherited features of Teacher class as well
as its own feature. Teacher Student

id id
name name
address address
marks
setId() setId()
getId() getId()
setName() setName()
getName() getName()
setAddr() setAddr()
getAddr() getAddr()
setMark()
getMark()
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Explanation
 When an object to class is created, it contains a copy of
class within it. This means there is a relation between
class and class objects.
 This is the reason why class members are available to
class. Note that we do not create class object, but still a copy of
it is available to class object.
 Here, we can observe that Student class-2 is smaller and easier to
develop. By using inheritance programmer can develop the classes very
easily. Hence programmer’s productivity is increased.
 The main advantage of inheritance is code reusability. A programmer
reuses the super class code without rewriting it, in creation of subclasses.

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Keyword: extends
 To inherit a class, you simply incorporate the definition of one class into
another by using the extends keyword.

 We can only specify one superclass for any subclass that you create. Java
does not support the inheritance of multiple superclasses into a single
subclass.
 We can create a hierarchy of inheritance in which a subclass becomes a
superclass of another subclass. However, no class can be a superclass of
itself.

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Simple Inheritance Example
class A { class SimpleInheritance {
int i, j; public static void main(String args[]) {
void showij() { A superOb = new A();
System.out.println("i and j: "+i+" "+j); superOb.i = 10;
} superOb.j = 20;
} System.out.println("Contents of superOb: ");
class B extends A { superOb.showij();
int k;
void showk() { B subOb = new B();
System.out.println("k: " + k); subOb.i = 7;
} subOb.j = 8;
void sum() { subOb.k = 9;
System.out.println("i+j+k:"+(i+j+k)); System.out.println("Contents of subOb: ");
} subOb.showij();
} subOb.showk();
System.out.println();
superOb subOb
10 i 7 i System.out.println("Sum of i,j,k in subOb:");
subOb.sum();
20 j 8 j }
}
9 k
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Output
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9

Sum of i, j and k in subOb:


i+j+k: 24

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Example-2 class RectWeight extends Rectangle
{
int weight;
class Rectangle RectWeight (int l, int w, int t) {
{ length = l ;
int length, width; width = w ;
Rectangle(int l, int w) { weight = t ;
length = l ; }
width = w ; }
} class RectWeightDemo {
Rectangle() { public static void main(String args[]) {
length = 0 ; RectWeight rw1 = new RectWeight(11, 5, 2 );
width = 0 ; RectWeight rw2 = new RectWeight(12, 10, 5);
} int AR;
int area()
AR = rw1.area();
{
System.out.println ("Area is " + AR);
return(length * width);
System.out.println ("Weight =" + rw1.weight);
}
} AR = rw2.area();
System.out.println ("Area is " + AR);
System.out.println ("Weight =" + rw2.weight);
}
}
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Example
Rectangle
 RectWeight inherits all of the characteristics of Rectangle
length
and adds to them the weight component. It is not width
necessary for RectWeight to re-create all of the features Rectangle()
Rectangle(int,int)
found in Rectangle. It can simply extend Rectangle to meet area()
its own purposes. RectWeight
 A major advantage of inheritance is that once you have length
width
created a superclass that defines the attributes common to weight
a set of objects, it can be used to create any number of Rectangle()
area()
more specific subclasses. RectWeight(int,int,int)
 Each subclass can precisely tailor its own classification. For
example, the following class inherits Rectangle and adds a
color attribute:

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Rectangle
Another subclass length
width
class ColorRect extends Rectangle Rectangle()
{ Rectangle(int,int)
int color; area()
ColorRect(int l, int w, int c) {
ColorRect
length = l ;
width = w ; length
color = c ; width
} color
} Rectangle()
area()
ColorRect(int,int,int)

 Remember, once you have created a superclass that defines the general
aspects of an object, that superclass can be inherited to form specialized
classes. Each subclass simply adds its own unique attributes. This is the
essence of inheritance.
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
'super' keyword

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


The keyword 'super'
 If we create an object of super class, we can access only the
super class members, but not sub class members. But if we
create sub class object, all the members of both super and sub
classes are available to it.
 Sometimes, the super class members and sub class members
may have same names. In that case, by default, only sub class
members are accessible.
 To access the super class members from sub class
keyword is introduced.

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Example without 'super'
class One{
int i = 10; //Super class variable
void show(){
System.out.println("Super class method: i = "+i);
}
}
class Two extends One{
int i = 20; //Sub class variable
void show(){
System.out.println("Sub class method: i = "+i);
}
}
class KeywordSuper{
public static void main(String args[]){
Two T = new Two();
T.show();
}
}
Output:
Sub class method: i = 20
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Use of 'super'
class One{
int i = 10; //Super class variable
void show(){
System.out.println("Super class method: i = "+i);
}
}
class Two extends One{
int i = 20; //Sub class variable
void show(){
System.out.println("Sub class method: i = "+i);
//using super to call super class method
super.show();
//using super to access super class variable
System.out.println("Super i = "+super.i);
}
}
class KeywordSuper{
public static void main(String args[]){
Two T = new Two(); Output:
T.show(); Sub class method: i = 20
} Super class method: i = 10
} Super i = 10
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Use of 'super'
 Here, it is clear that can be used to refer to super class variable as
well as super class method.
 'super' keyword can be used to refer to super class constructor. We need
not call the default constructor of the super class, as it is by default
available to sub class.
 To call the parameterized constructor, we can write:

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Default constructor in inheritance
class One{
One(){ //super class default constructor
Here, we can observe that
System.out.println("One"); when sub-class object is
}
}
created, first of all the
class Two extends One{ super-class default
Two(){ //sub class default constructor
System.out.println("Two"); constructor is called and
} then only the sub-class
}
class Super1{ constructor is called.
public static void main(String args[]){
Two T = new Two();
}
}
Output:
One
Two

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Use of 'super' to call parameterized constructor
class One{ One condition is that the
int i;
One(int i){ //super class default constructor statement calling the
this.i = i;
} super-class constructor
} should be the first one in
class Two extends One{
int i; the sub-class constructor.
Two(int a, int b){
super(a); //call super class constructor This implies that the
i = b; //initialize sub class i super-class constructor
}
void show(){ should be given priority
System.out.println("Sub class i = "+i);
System.out.println("Super class i = "+super.i);
over the sub-class
} constructor.
}
class Super1{
public static void main(String args[]){
Two T = new Two(8, 12); Output:
T.show(); Sub class i = 12
} Super class i = 8
}
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
protected specifier

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Member Access and Inheritance
 Although a subclass includes all of the members of its superclass, it
cannot access those members of the superclass that have been declared
as private.
class A { class B extends A {
int i ; //public by default int total;
private int j ; //private to A void sum() {
total = i + j ; //ERROR, j is not accessible
void setij (int x, int y) {
}
i = x;
}
j = y; class Access {
} public static void main(String args[]) {
} B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Member Access and Inheritance
 This program will not compile because the use of j inside the sum( )
method of B causes an access violation. Since j is declared as private, it is
only accessible by other members of its own class. Subclasses have no
access to it.

 REMEMBER
A class member that has been declared as private will remain private to its
class. It is not accessible by any code outside its class, including subclasses.

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


'protected' specifier
 The private members of the super class are not available to
sub classes directly. But sometimes there may be a need to
access the data of super class in the sub class.
 For this purpose, protected specifier is used. protected is
commonly used in super class to make the members of the
super class available directly in its sub classes. We can think that
protected specifier works like public with respect to sub
classes.

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


'protected' specifier
class Mainclass{
private int a;
protected int b;
}
class Subclass extends Mainclass{
public void get(){
System.out.println("a=" + a);
System.out.println("b=" + b);
}
}
class Testclass{
public static void main(String ar[]){
Subclass s = new Subclass();
s.get();
}
}
Testclass.java:7: error: a has private access in Mainclass
System.out.println("a="+a);
^
1 error
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Types of Inheritance

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Types of Inheritance
 There are three types of inheritance supported by Java:
1. Single inheritance
2. Multilevel inheritance
3. Hierarchical inheritance

A A A

B B D C
B
Single E F
Inheritance C
Multi-level Hierarchical Inheritance
Inheritance
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Multi-level Inheritance
Rectangle
 We can build hierarchies that contain as many layers length
of inheritance as you like. As mentioned, it is width
Rectangle()
perfectly acceptable to use a subclass as a superclass Rectangle(int,int)
area()
of another.
RectWeight
 For example, given three classes called Rectangle, length
RectWeight and Shipment, Shipment can be a width
weight
subclass of RectWeight, which is a subclass of area()
Rectweight()
Rectangle. RectWeight(int,int,int)

 When this type of situation occurs, each subclass Shipment

inherits all of the traits found in all of its super length


width
classes. In this case, Shipment inherits all aspects of weight
cost
RectWeight and Rectangle. area()
Shipment()
Shipment(int,int,int,int)
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Multi-level Inheritance Example
class Rectangle //Add weight
{ class RectWeight extends Rectangle {
protected int length; protected int weight;
protected int width;
Rectangle() { RectWeight() {
length = 0; super();
width = 0; weight = -1 ;
} }
Rectangle(int l, int w) {
length = l ; RectWeight(int l, int w, int t) {
width = w ; super(l, w);
} weight = t ;
Rectangle(Rectangle ob) { }
length = ob.length ;
width = ob.width ; RectWeight(RectWeight ob) {
} super(ob);
int area() weight = ob.weight ;
{ }
return (length * width); }
}
}
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Multi-level Inheritance Example
// Add shipping cost class DemoShipment {
class Shipment extends RectWeight { public static void main(String args[]) {
double cost; Shipment sp1 = new Shipment(10, 5, 4, 100.0 );
Shipment() { Shipment sp2 = new Shipment(11, 8, 10, 250.50);
super(); int AR;
cost= 0;
} AR = sp1.area();
Shipment(int l,int w,int t, double c){ System.out.println ("Shipment Area is " + AR);
super(l, w, t); System.out.println ("Weight =" + sp1.weight);
cost = c ; System.out.println ("Ship-Cost=" + sp1.cost);
}
AR = sp2.area();
Shipment(Shipment ob) { System.out.println ("Shipment Area is " + AR);
super(ob); System.out.println ("Weight =" + sp2.weight);
cost = ob.cost; System.out.println ("Ship-Cost=" + sp2.cost);
} }
} }
Output:

Prac-18_B
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Explanation
 Here, the subclass RectWeight is used as a superclass to create the subclass
called Shipment. Shipment inherits all of the traits of RectWeight and
Rectangle, and adds a field called cost, which holds the cost of shipping such a
parcel.
 Because of inheritance, Shipment can make use of the previously defined
classes of Rectangle and RectWeight, adding only the extra information it
needs for its own, specific application.
 This is part of the value of inheritance; it allows the reuse of code. This example
illustrates one other important point: super( ) always refers to the constructor
in the closest superclass. The super( ) in Shipment calls the constructor in
RectWeight. The super( ) in RectWeight calls the constructor in Rectangle.
 In a class hierarchy, if a superclass constructor requires parameters, then all
subclasses must pass those parameters "up the line." This is true whether or
not a subclass needs parameters of its own.
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Hierarchical Inheritance

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Hierarchical Inheritance Example
class Employee{ class Manager extends Employee{
protected String name; String title;
protected int no; int dues;
void getdata(String nm, int n){ void getdata(String nm,int n,String t,int d){
name = nm; super.getdata(nm,n);
no = n; title = t;
} dues = d;
void putdata(){ }
System.out.println("Name: "+name); void putdata(){
System.out.println("Number: "+no); super.putdata();
} System.out.println("Title: "+title);
} System.out.println("Club dues: "+dues);
class Scientist extends Employee{ }
int pubs; }
void getdata(String nm,int n,int pb){
super.getdata(nm,n); class Laborer extends Employee{
pubs = pb; }
}
void putdata(){
super.putdata();
System.out.println("Publications: "+pubs);
}
}
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Hierarchical Inheritance Example
class Hierarchy1{
public static void main(String args[]){ Name: Thomas
Number: 192
Manager m1 = new Manager();
Title: HR
m1.getdata("Thomas",192,"HR",15000); Club dues: 15000
m1.putdata(); Name: Romin
Manager m2 = new Manager(); Number: 328
m2.getdata("Romin",328,"MD",50000); Title: MD
m2.putdata(); Club dues: 50000
Scientist s = new Scientist(); Name: V.Rao
s.getdata("V.Rao", 132, 45); Number: 132
s.putdata(); Publications: 45
Name: Manu
Laborer lb = new Laborer();
Number: 440
lb.getdata("Manu", 440);
lb.putdata();
}
}

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Hierarchical Inheritance Example-2
staff
code
name

teacher typist officer


subject speed grade

regular contract
daily wages

Prac-18_C
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Hierarchical Inheritance Example-2
class Staff{ class Typist extends Staff{
protected int code; int speed;
protected String name; void getdata(int c,String nm,int sp){
void getdata(int c,String nm){ super.getdata(c,nm);
code = c; speed = sp;
name = nm; }
} void show(){
void show(){ super.show();
System.out.println("Staff Code:"+code); System.out.println("Typist's Speed:"+speed);
System.out.println("Staff Name: "+name); }
} }
}

class Teacher extends Staff{ class Officer extends Staff{


String subject; String grade;
void getdata(int c,String nm,String sub){ void getdata(int c,String nm,String gr){
super.getdata(c,nm); super.getdata(c,nm);
subject = sub; grade = gr;
} }
void show(){ void show(){
super.show(); super.show();
System.out.println("Teacher Subject:"+subject); System.out.println("Officer Grade:"+grade);
} }
} }
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Hierarchical Inheritance Example-2
class RegTypist extends Typist{ class Hierarchy{
void getdata(int c,String nm,int sp){ public static void main(String args[]){
super.getdata(c,nm,sp); Teacher t = new Teacher();
} t.getdata(11,"C A Gajjar","Java");
void show(){ t.show();
super.show();
} Officer off = new Officer();
} off.getdata(103,"D R Gandhi","Class-2");
class ContractTypist extends Typist{ off.show();
int wages;
void getdata(int c,String nm,int sp,int wg){ ContractTypist ct = new ContractTypist();
super.getdata(c,nm,sp); ct.getdata(202, "Rajesh", 55, 150);
wages = wg; ct.show();
} }
void show(){ }
super.show();
Staff Code:11 Staff Code:202
System.out.println("Typist Daily Wage:"+wages); Staff Name: C A Gajjar Staff Name: Rajesh
} Teacher's Subject:Java Typist's Speed:55
} Staff Code:103 Typist's Daily Wage:150
Staff Name: D R Gandhi
Officer's Grade:Class-2

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Polymorphism

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Polymorphism
 Polymorphism cam from the two Greek words ‘poly’ meaning many and
‘morphos’ meaning forms.
 The ability to exist in different forms is called polymorphism. For example,
an operation may exhibit different behavior in different instances.
 The behavior depends upon the types of data used in the operation. For
example, consider the addition operation. For two numbers, the
operation will generate a sum. If the operands are strings, then the
operation would produce a third string by concatenation.
 Polymorphism is extensively used in implementing inheritance.

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Types of polymorphism
 There are two types of polymorphism in Java:
1. Compile Time Polymorphism:
Compile-time polymorphism is also known as static polymorphism and
it is implemented by method overloading. It allows users to define
multiple methods with the same name but different parameters. It is
beneficial because it helps write cleaner and more efficient code.
2. Run Time Polymorphism:
Run time polymorphism is also known as dynamic method dispatch and
it is implemented by the method overriding.

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Method Overloading
 Method overloading, which enables the coexistence of many methods
with the same name but distinct parameter lists within a class, enables
Java to accomplish compile-time polymorphism.
 In method overloading, the methods with the same name can have
different numbers of parameters, different types of parameters, or
different order of parameters in methods.
 Programmers can use method overloading to create numerous methods
with the same name but different parameters that are all included within
the same class. Depending on the arguments used during the method
call, the compiler chooses the right method to call.

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Method Overloading
class MathOperation { In the above example, the
// Method with two int parameters
public int multiply(int a, int b) {
‘MathOperation’ class has
return a * b; three methods named
} ‘multiply’. The first
// Method with same name but different types of parameters method multiplies two
public double multiply(double a, double b) {
return a * b; integers, the second
} multiplies two double
// Method with the same name but 3 parameters values and the third
public int multiply(int a, int b, int c) {
return a * b * c;
multiplies three integers.
} When ‘multiply’ is called
} from the ‘main’ method,
class MultiplyMethodOverload {
the suitable version of
public static void main(String ar[]) {
MathOperation op = new MathOperation(); ‘multiply’ based on the
System.out.println(op.multiply(4, 5)); // Calls first method number and types of
System.out.println(op.multiply(4.5, 5.5)); // Calls second method arguments used is
System.out.println(op.multiply(4, 5, 6)); // Calls third method
} processed.
}
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Method Overriding
 It is a type of runtime polymorphism where the method in the subclass
overrides the method in the superclass, which has the same name,
parameters, and return type. Here, the method to be called is based on
the instance of the subclass, which is assigned to a reference variable of
the superclass.
 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 its 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.
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Method Overriding
class A { class Override {
int i, j; public static void main(String args[]) {
A(int a, int b) { B subOb = new B(1, 2, 3);
i = a; subOb.show(); //this calls show() in B
j = b; }
} }
void show() {
System.out.println("i and j: "+i+" "+j);
Output:
} k: 3
class B extends A {
int k; Method overriding occurs only
B(int a, int b, int c) {
super(a, b); when the names and the type
k = c; signatures of the two methods are
}
//display k - it overrides show() in A identical. If they are not, then the
void show() {
System.out.println("k: " + k);
two methods are simply overloaded.
}
}
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Explanation
 When show( ) is invoked on an class B extends A {
object of type B, the version of int k;
show( ) defined within B is used. B(int a, int b, int c) {
That is, the version of show( ) inside super(a, b);
B overrides the version declared in k = c;
A. }
void show() {
 If we wish to access the superclass
super.show();
version of an overridden method,
//this calls A's show()
we can do so by using super. For System.out.println("k:"+k);
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.
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
class Shape{ class Square extends Shape{
void draw(){ void draw(){
System.out.println("Drawing a shape"); System.out.println("Drawing a Square");
} }
void erase(){ void erase(){
System.out.println("Erasing a shape"); System.out.println("Erasing a Square");
} }
} }
class Circle extends Shape{ class TestShape{
void draw(){ public static void main(String ar[]){
System.out.println("Drawing a Circle"); Shape Cir = new Circle();
} Shape Tri = new Triangle();
void erase(){ Shape Squ = new Square();
System.out.println("Erasing a Circle"); Cir.draw();
}
} Cir.erase();
class Triangle extends Shape{ Tri.draw();
void draw(){ Tri.erase();
System.out.println("Drawing a Triangle"); Squ.draw();
} Squ.erase();
void erase(){ }
System.out.println("Erasing a Triangle"); }
}
}
Prac-19
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Dynamic Method Dispatch
 Method overriding forms the basis for one of Java’s most powerful concepts:
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. Dynamic method dispatch is important because this is how Java
implements run-time polymorphism.

 An important principle: a superclass reference variable can refer to a subclass


object. Java uses this fact to resolve calls to overridden methods at run time.

 How? 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.
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Dynamic Method Dispatch
 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.

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Dynamic Method Dispatch
class A { class Dispatch {
void callme() { public static void main(String args[]) {
System.out.println("Inside A's callme method"); A a = new A(); // object of type A
} B b = new B(); // object of type B
} C c = new C(); // object of type C
class B extends A {
// override callme() A r; //obtain a reference of type A
void callme() { r = a; //r refers to an A object
System.out.println("Inside B's callme method"); r.callme(); //calls A's version of callme
} r = b; //r refers to a B object
} r.callme(); //calls B's version of callme
class C extends A { r = c; //r refers to a C object
// override callme() r.callme(); //calls C's version of callme
void callme() { }
System.out.println("Inside C's callme method"); }
}
}
Output:
Inside A's callme method
Inside B's callme method
Inside C's callme method
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Dynamic Method Dispatch
 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.
NOTE: Readers familiar with C++ or C# will recognize that overridden methods in Java are
similar to virtual functions in those languages.

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Real Time example of Method Overriding

class Figure
class Rectangle extends Figure
class Triangle extends Figure

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Real Time example of Method Overriding
class Figure { class Triangle extends Figure {
double dim1; Triangle(double a, double b) {
double dim2; super(a, b);
Figure(double a, double b) { }
dim1 = a; double area() { //override area for triangle
dim2 = b; System.out.println("Inside Area of Triangle");
} return dim1 * dim2 / 2;
double area() { }
System.out.println("Area of Figure is undefined."); }
return 0; class FindAreas {
} public static void main(String args[]) {
} Figure f = new Figure(10, 10);
class Rectangle extends Figure { Rectangle r = new Rectangle(9, 5);
Rectangle(double a, double b) { Triangle t = new Triangle(10, 8);
super(a, b); Figure figref;
} figref = r;
double area() { //override area for rectangle System.out.println("Area is "+figref.area());
System.out.println("Inside Area for Rectangle."); figref = t;
return dim1 * dim2; System.out.println("Area is "+figref.area());
} figref = f;
} System.out.println("Area is "+figref.area());
}
Prac-20
}
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Method Overloading vs Method Overriding
Method Overloading Method Overriding
Writing two or more methods with the same Writing two or more methods with the same
name but with different signatures is called name and same signatures is called method
method overloading. overriding.
Method overloading is done in the same class. Method overriding is done in inheritance:
superclass and sub classes.
In method overloading, method return type can In method overriding, method return types should
be same or different. also be same.
JVM decides which method is called depending on JVM decides which method is called depending on
the difference in the method signatures. (Number the data type(class) of the object used to call the
of arguments and types, sequence of arguments) method.
Method overloading is done when the Method overriding is done when the programmer
programmer wants to extend the already available wants to provide a different implementations
feature. (body) for the same feature.
Method overloading is code refinement. Same Method overriding is code replacement. The sub
method is refined to perform a different task. class method overrides (replaces) the super class
method.
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Abstract class

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Using Abstract method
 There are situations in which we want to define a superclass that declares
the structure of a given abstraction without providing a complete
implementation of every method.
 That is, sometimes we want to create a superclass that only defines a
generalized form that will be shared by all of its subclasses, leaving it to
each subclass to fill in the details.
 Such a class determines the nature of the methods that the subclasses
must implement. One way this situation can occur is when a superclass is
unable to create a meaningful implementation for a method. This is the
case with the class Figure used in the preceding example. The definition
of area( ) is simply a placeholder. It will not compute and display the area
of any type of object.
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Using Abstract method
 As we create our own class libraries, it is not uncommon for a method to
have no meaningful definition in the context of its superclass. We can
handle this situation two ways:
 One way, as shown in the previous example, is to simply have it report a
warning message. While this approach can be useful in certain
situations—such as debugging—it is not usually appropriate. We may
have methods that must be overridden by the subclass in order for the
subclass to have any meaning.
 Consider the class Triangle. It has no meaning if area( ) is not defined. In
this case, we want some way to ensure that a subclass does, forcefully,
override all necessary methods. Java’s solution to this problem is the
abstract method.
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Using Abstract method
 We can require that certain methods be overridden by subclasses by
specifying the abstract type modifier. These methods are sometimes
referred to as subclasser responsibility because they have no
implementation specified in the superclass.
 Thus, a subclass must override them—it cannot simply use the version
defined in the superclass. To declare an abstract method, use this general
form:
abstract type name(parameter-list);
 As we can see, no method body is present.
 Any class that contains one or more abstract methods must also be
declared abstract.
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Using Abstract class
 There can be no objects of an abstract class. That is, an abstract class
cannot be directly instantiated with the new operator. Such objects
would be useless, because an abstract class is not fully defined.

 Also, we cannot declare abstract constructors, or abstract static methods.


Any subclass of an abstract class must either implement all of the
abstract methods in the superclass, or be declared abstract itself.

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Abstract Class Example
// A Simple demonstration of abstract class.
abstract class A {
abstract void callme();
void callmetoo() { //concrete methods still allowed in abstract classes
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Using Abstract Class
 Notice that no objects of class A are declared in the program. As mentioned, it
is not possible to instantiate an abstract class.
 One other point: class A implements a concrete method called callmetoo( ).
This is perfectly acceptable. Abstract classes can include as much
implementation as they see fit.

 Although abstract classes cannot be used to instantiate objects, they can be


used to create object references, because Java’s approach to run-time
polymorphism is 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 subclass object.

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Using Abstract Class class Triangle extends Figure {
abstract class Figure { Triangle(double a, double b) {
double dim1; super(a, b);
double dim2;
}
Figure(double a, double b) {
dim1 = a; double area() { //override area for triangle
dim2 = b; System.out.println("Inside Triangle Area.");
} return dim1 * dim2 / 2;
abstract double area(); }
} }
class Rectangle extends Figure { class AbstractAreas {
Rectangle(double a, double b) { public static void main(String args[]) {
super(a, b);
// Figure f = new Figure(10, 10); ILLEGAL NOW
}
double area() { //override area for Rectangle Rectangle r = new Rectangle(9, 5);
System.out.println("Inside Rectangle Area."); Triangle t = new Triangle(10, 8);
return dim1 * dim2;
} Figure figref;
} figref = r;
System.out.println("Area is"+figref.area());
figref = t;
System.out.println("Area is"+figref.area());
}
Prac-21 }
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Explanation
 As the comment inside main( ) indicates, it is no longer possible to
declare objects of type Figure, since it is now abstract. And, all subclasses
of Figure must override area( ). To prove this to yourself, try creating a
subclass that does not override area( ). You will receive a compile-time
error.
 Although it is not possible to create an object of type Figure, you can
create a reference variable of type Figure. The variable figref is declared
as a reference to Figure, which means that it can be used to refer to an
object of any class derived from Figure. As explained, it is through
superclass reference variables that overridden methods are resolved at
run time.

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


'final' keyword

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


Using 'final' keyword with Inheritance
 The keyword final has three uses. First, it can be used to create the
equivalent of a named constant.
 For example: final int SIZE = 100;
final double PI = 3.142;
 Final variables behave like class variables and they do not take any space
on individual objects of the class.

 The other two uses of final apply to inheritance:


1. Using final to Prevent Overriding
2. Using final to Prevent Inheritance

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


final at variable level
class Person{ Here, if we are trying to edit p.name = "Punit";
private final String name; then the compiler generates error because we are
private int age; trying to edit final variable.

error: cannot assign a value to final variable name


Person(String name, int age){ p.name = "Punit";
this.name = name; ^
this.age = age; 1 error
}
void printData(){
System.out.println("Name: "+name);
System.out.println("Age: "+age);
}
public static void main(String ar[]){
Person p = new Person("Romesh",34);
p.printData();
//p.name = "Punit";
}
}
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Using final to Prevent Overriding
 While method overriding is one of Java’s most powerful features, there
will be times when we want to prevent it from occurring. To disallow a
method from being overridden, specify final as a modifier at the start of
its declaration. Methods declared as final cannot be overridden.
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


final at method level
class Person{ class Detail extends Person{
protected String name; Detail(String name,int age){
protected int age; super(name,age);
}
Person(String name, int age){ void sayHello(){
this.name = name; System.out.println("Hello,"+this.name);
this.age = age; }
} }
void printData(){
System.out.println("Name: "+name); Final.java:25: error: sayHello() in Detail cannot override
System.out.println("Age: "+age); sayHello() in Person
} void sayHello(){
final void sayHello(){ ^
System.out.println("Hello World"); overridden method is final
} 1 error
public static void main(String ar[]){
Person p = new Person("Romesh",34);
p.sayHello();
}
}
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Using final to Prevent Inheritance
 Sometimes we want to prevent a class from being inherited. To do this,
precede the class declaration with final. Declaring a class as final
implicitly declares all of its methods as final, too.
 As we might expect, it is illegal to declare a class as both abstract and
final since an abstract class is incomplete by itself and relies upon its
subclasses to provide complete implementations.
final class A {
//...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
//...
}

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


final at class level
final class Person{ class Employee extends Person{
protected String name; private int salary;
protected int age; Employee(String name,int age,int salary){
super(name,age);
Person(String name, int age){ this.salary = salary;
this.name = name; }
this.age = age; int getSalary(){
} return this.salary;
void printData(){ }
System.out.println("Name: "+name); }
System.out.println("Age: "+age);
}
public static void main(String ar[]){
Final.java:18: error: cannot inherit from final Person
Person p = new Person("Romesh",34); class Employee extends Person{
p.printData(); ^
} 1 error
}

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat


class Car{ class TestCar{
protected String RTOno; public static void main(String ar[]){
protected String Owner; Car A = new Car();
void getdata(String no,String ow){ A.getdata("GJ05AB1234","Romesh");
RTOno = no; A.printData();
Owner = ow; HondaCity hc = new HondaCity();
} hc.getdata("GJ05DD4567","Ajit",1500);
final void printData(){ hc.printDetail();
System.out.println("RTO No: "+RTOno); }
System.out.println("Owner: "+Owner); }
}
}
class HondaCity extends Car{
private int cc; Use of 'super' & 'final'
void getdata(String no,String ow,int c){
super.getdata(no,ow); keywords in program.
cc = c;
}
void printDetail(){
System.out.println("RTO No: "+RTOno);
System.out.println("Owner: "+Owner);
System.out.println("Engine CC: "+cc);
}
} Prac-24
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
The Object Class
 There is one special class, Object, defined by Java. All other
classes are subclasses of java.lang.Object class. i.e. Object
is the super class of all the classes (pre-defined and user-
defined) by default.
 That is, Object is a superclass of all other classes. This means
that a reference variable of type Object can refer to an object of
any other class. The Object class provides some common
behaviors to all the objects: object comparison, cloning, notified
etc.
 Also, since arrays are implemented as classes, a variable of type
Object can also refer to any array.
Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat
Methods of Object class
Method Description
int hashCode() Return the hash code of the object.
Object clone() A copy of the object is created and returned.
boolean equals(object o) Checks whether an object is equal to another or not. If both references refer to
the same object, they are equal, else not.
void finalize() Used by classes to dispose of their occupied resources.
final class getClass() Returns the class of the object.
final void notify() Used by threads, to wake up a thread that is in waiting state.
final void notifyAll() Used by threads, to wake up all the threads in waiting state
String toString() A string definition(representation) of the object is returned.
final void wait() Puts the current thread in waiting state.
final void wait(long time) Puts the current thread in waiting state for the specified time.
final void wait(long time, Puts the current thread in waiting state for the specified amount of real time.
int n)

Chintan Gajjar, ITD, Dr S & S S Ghandhy College, Surat

You might also like