Module 3
Module 3
Module-3
Inheritance
Inheritance is one of the building blocks of object oriented programming languages. It is the mechanism
in Java by which one class is allowed to inherit the features(fields and methods) of another class. In
Java, Inheritance means creating new classes based on existing ones. A class that inherits from
another class can reuse the methods and fields of that class. In the terminology of Java, a class that is
inherited is called a super class. The class that does the inheriting is called a subclass. Therefore, a
sub class is a specialized version of a superclass. It inherits all of the instance variables and methods
defined by the superclass and add its own, unique elements. Through inheritance, one can achieve re-
usability of the code.
Class A
{
int i,j;
void showij()
{
System.out.println("iandj:"+i+""+j);
}
}
Class B extends A
{
Int k;
void showk()
{
System.out.println("k:"+k);
}
Void sum()
{
System.out.println("i+j+k:"+(i+j+k));
}
}
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 2
Class SimpleInheritance
{
Public static void main(String args[])
{
A superOb=new A();
B subOb=new B();
superOb.i = 10;
superOb.j=20;
System.out.println("ContentsofsuperOb:");
superOb.showij();
subOb.i=7;
subOb.j=8;
subOb.k=9;
System.out.println("ContentsofsubOb:");
subOb.showij();
subOb.showk();
System.out.println("Sumofi,jandkinsubOb:"); subOb.sum();
}
}
Note that, private members of the super class can not be accessed by the sub class. The subclass
contains all non-private members of the super class and also it contains its own set of members to
achieve specialization.
Type of Inheritance
• Single Inheritance:If a class is inherited from one parent class,then it is known as single
inheritance. This will be of the form as shown below –
superclass
subclass
• Multilevel Inheritance:If several classes are inherited one after the other in a hierarchical
manner, it is known as multilevel inheritance, as shown below – For example program refer multi
level hierarchy program
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 3
• Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In
the below image, class A serves as a base class for the derived classes B, C, and D.
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 4
• Multiple Inheritance
In Multiple inheritances, one class can have more than one superclass and inherit features from
all parent classes. Please note that Java does not support multiple inheritances with classes. In
Java, we can achieve multiple inheritances only through Interfaces. In the image below, Class C
is derived from interfaces A and B.
• Hybrid Inheritance
Hybrid means consist of more than one. Hybrid inheritance is the combination of two or more
types of inheritance.
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 5
Class Base
{
void dispB()
{
System.out.println("Superclass");
}
}
Class Derived extends Base
{
void dispD()
{
System.out.println("Subclass");
}
}
Class Demo
{
Public static void main(String args[])
{
Base b=new Base();
Derived d=new Derived();
Note that, the type of reference variable decides the members that can be accessed, but not the type
of the actual object. That is, when a reference to a subclass object is assigned to a superclass
reference variable, you will have access only to those parts of the object defined by the superclass.
Using super
In Java,the keyword super can be used in following situations:
• To invoke super class constructor within the sub class constructor
• To access superclass member (variable or method) when there is a duplicate member name in
the subclass(both super and sub class member names are same).
Class Box
{
Double w,h,b;
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 6
Box(doublewd,doubleht,double br)
{
w=wd;h=ht;b=br;
}
}
Class ColourBox extends Box
{
Int colour;
ColourBox(double wd,double ht,double br,int c)
{
w=wd;
h=ht;
b=br; //code redundancy
colour=c;
}
}
Also,if the data members of super class are private, then we can’t even write such a code in subclass
constructor. If we use super() to call superclass constructor, then it must be the first statement
executed inside a subclass constructor as shown below –
Class Box
{
Double w,h,b;
Box(double wd,double ht,double br)
{
w=wd;
h=ht;
b=br;
}
}
Class Demo
{
Public static void main(String args[])
{
ColourBox b=new ColourBox(2,3,4,5);
}
}
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 7
Here, we are creating the object b of the subclass ColourBox. So, the constructor of this class is
invoked. As the first statement within it is super(wd, ht, br), the constructor of superclass Box is
invoked, and then the rest of the statements in subclass constructor ColourBox are executed.
• To access superclass member variable when there is a duplicate variable name in the
subclass: This form of super is most applicable to situations in which member names of a
subclass hide members by the same name in the superclass.
Class A
{
int a;
}
Class B extends A
{
int a; //duplicate variablea
B(int x,int y)
{
super.a=x; //accessing superclass a
a=y; //accessing own member a
}
Void disp()
{
System.out.println("superclassa:"+super.a);
System.out.println("sub class a: "+ a);
}
}
Class SuperDemo
{
Public static void main(String args[])
{
B ob=new B(2,3);
ob.disp();
}
}
Class A
{ int a;
}
Class B extends A
{ int b;
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 8
Class C extends B
{ int c;
Class MultiLevel
{
Public static void main(String args[])
{
C ob=new C(2,3,4);
ob.disp();
}
}
Class A
{
A()
{
System.out.println("A'sconstructor.");
}
}
Class B extends A
{
B()
{
System.out.println("B'sconstructor.");
}
}
Class C extends B
{
C() {
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 9
}
} System.out.println("C'sconstructor.");
Class CallingCons
{
Public static void main(String args[])
{
C c = new C();
}
}
Output:
A'sconstructor
B'sconstructor
C'sconstructor
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 10
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.
Class A
{
int i,j;
A(int a,int b)
{
i=a;
j=b;
}
Void show() //suppressed
{
System.out.println("iandj:"+i+""+j);
}
}
Class B extends A
{
int k;
B(int a,int b,int c)
{
super(a,b);
k = c;
}
Void show() //Overridden method
{
System.out.println("k:"+k);
}
}
Class Override
{
Public static void main(String args[])
{
B subOb=new B(1,2,3);
subOb.show();
}
}
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 11
Output:
k:3
Note that, above program, only subclass method show() got called and hence only k got displayed.That
is, the show() method of super class is suppressed.If we want superclass method also to be called, we
can re-write the show() method in subclass as –
voidshow()
{
super.show(); //this calls A's show()
System.out.println("k:"+k);
}
Method overriding occurs only when the names and the type signatures of the two methods (one in
superclass and the other in subclass) are identical. If two methods (one in superclass and the other in
subclass) have same name, but different signature, then the two methods are simply overloaded.
Class A
{
void callme()
{
System.out.println("InsideA");
}
}
Class B extends A
{
void callme()
{
System.out.println("InsideB");
}
}
Class C extends A
{
Void callme()
{
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 12
System.out.println("InsideC");
}
}
Class Dispatch
{
Public static void main(String args[])
{
A a = new A();
B b = new B();
C c = new C();
A class containing at least one abstract method is called as abstract class. Abstract classes cannot be
instantiated, that is one cannot create an object of abstract class. Where as, a reference can be created
for an abstract class.
Abstract class A
{
Abstract void callme();
void callmetoo()
{
System.out.println("Thisisaconcretemethod.");
}
}
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 13
Class B extends A
{
Void callme()//overriding abstract method
{
System.out.println("B'simplementationofcallme.");
}
}
Class AbstractDemo
{
Public static void main(String args[])
{
B b = new B();//subclass object
b.callme(); //calling abstract method
b.callmetoo();//calling concrete method
}
}
Example: Write an abstract class shape, which has an abstract method area(). Derive three classes
Triangle, Rectangle and Circle from the shape class and to override area(). Implement run-time
polymorphism by creating array of references to supeclass.Compute area of different shapes and display
the same.
Solution:
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 14
Class AbstractDemo
{
Public static void main(String args[])
{
Shaper[]={new Triangle(3,4),new Rectangle(5,6),new Circle(2)};
for(int i=0;i<3;i++)
System.out.println(r[i].area());
}
}
Output:
Area of Triangle is:6.0
AreaofRectangleis:30.0
Area of Circle is:12.5664
Note that, here we have created array r, which is reference to Shape class. But, every element in r is
holding objects of different subclasses. That is, r[0] holds Triangle class object, r[1]holds Rectangle class
object and so on. With the help of array initialization, we are achieving this, and also, we are calling
respective constructors. Later, we use a for-loop to invoke the method area() defined in each of these
classes.
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 15
Using final
The keyword final can be used in three situations in Java:
• To create the equivalent of a named constant.
• To prevent method overriding
• To prevent Inheritance
To create the equivalent of a named constant: A variable can be declared as final.Doing so prevents
its contents from being modified. This means that you must initialize a final variable when it is declared.
For example:
final int FILE_NEW = 1;
final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
finalintFILE_SAVEAS=4;
final int FILE_QUIT = 5;
It is a common coding convention to choose all uppercase identifiers for final variables. Variables
declared as final do not occupy memory on a per-instance basis. Thus, a final variable is essentially a
constant.
To prevent Inheritance: As we have discussed earlier, the subclass is treated as a specialized class
and superclass is most generalized class. During multi-level inheritance, the bottom most class will be
with all the features of real-time and hence it should not be inherited further. In such situations, we can
prevent a particular class from inheriting further, using the keyword final. For example –
Final class A
{
// ...
}
Class B extends A //ERROR! Can't subclass A
{
// ...
}
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 16
Note:
• Declaring a class as final implicitly declares all of its methods as final, too.
• 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
import java.util.List;
public class Tester {
public static void main(String[] args) {
var names = List.of("Julie", "Robert", "Chris", "Joseph");
for (var name : names) {
System.out.println(name);
}
System.out.println("");
for (var i = 0; i < names.size(); i++) {
System.out.println(names.get(i));
}
}}
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 17
Method Purpose
Object clone() Creates a new object that is the same as the object being cloned.
Void notifyAll() Resumes execution of all threads waiting on the invoking object.
The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You may override
the others. The equals( ) method compares the contents of two objects. It returns true if the objects
are equivalent, and false otherwise. The precise definition of equality can vary, depending on the
type of objects being compared. The toString() method returns a string that contains a description of
the object on which it is called. Also, this method is automatically called when an object is output
using println( ). Many classes override this method.
Interfaces
Interface is an abstract type that can contain only the declarations of methods and constants(By default
public abstract methods and Final static variables). Interfaces are syntactically similar to classes, but they
do not contain instance variables, and their methods are declared without any body. Any number of
classes can implement an interface. One class may implement many interfaces. By providing the
interface keyword, Java allows you to fully utilize the “one interface, multiple methods” aspect of
polymorphism. Interfaces are alternative means for multiple inheritance in Java.
Defining an Interface
An interface is defined much like a class. This is the general form of an interface:
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 18
return-type method-name2(parameter-list);
…………………
}
interface ICallback
{
void callback(int param);
}
class TestIface
{
public static void main(String args[])
{
ICallback c = new Client();
c.callback(42);
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 19
// c.test() //error!!
}
}
Here, the interface ICallback contains declaration of one method callback(). The class Client
implementing this interface is defining the method declared in interface. Note that, the method callback()
is public by default inside the interface. But, the keyword public must be used while defining it inside the
class. Also, the class has its own method test(). In the main() method, we are creating a reference of
interface pointing to object of Client class. Through this reference, we can call interface method, but not
method of the class.
The true polymorphic nature of interfaces can be found from the following example –
interface ICallback
{
void callback(int param);
}
class TestIface
{
public static void main(String args[])
{
ICallback x[]={new Client(), new Client2()};
for(int i=0;i<2;i++)
x[i].callback(5);
}
}
Output:
callback called with 5
Another version of ICallBack
p squared 25
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 20
In this program, we have created array of references to interface, but they are initialized to class objects.
Using the array index, we call respective implementation of callback() method.
Note: Interfaces may look similar to abstract classes. But, there are lot of differences between them as
shown in the following table:
Abstract Class Interface
Can have instance methods that implements Are implicitly abstract and cannot have
a default behavior. implementations.
Can have the members with private, Members of a Java interface are public by
protected, etc.. default.
Variables in Interfaces
You can use interfaces to import shared constants into multiple classes by simply declaring an interface
that contains variables that are initialized to the desired values. When you include that interface in a class
all of those variable names will be in scope as constants (Similar to #define in C/C++). If an interface
contains no methods, then any class that includes such an interface doesn’t actually implement anything.
It is just using a set of constants. Consider an example to illustrate the same:
interface SharedConst
{
int FAIL=0; //these are final by default
int PASS=1;
}
Result(double m)
{
mr=m;
}
int res()
{
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 21
if(mr<40)
return FAIL;
else return PASS;
}
}
class Exam extends Result implements SharedConst
{
Exam(double m)
{
super(m);
}
public static void main(String args[])
{
Exam r = new Exam(56);
switch(r.res())
{
case FAIL:
System.out.println("Fail");
break;
case PASS:
System.out.println("Pass");
break;
}
}
}
interface A
{
void meth1();
void meth2();
}
interface B extends A
{
void meth3();
}
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 22
{
System.out.println("Implement meth2().");
}
public void meth3()
{
System.out.println("Implement meth3().");
}
}
class IFExtend
{
public static void main(String arg[])
{
MyClass ob = new MyClass();
ob.meth1();
ob.meth2();
ob.meth3();
}
}
Before java 8,interfaces could have only abstract methods.The implementation of these methods has
to be provided in a separate class.So,if a new method is to be added in an interface,then its
implementation code has to be provided in the class implementing the same interface.To overcome
this issue,java 8 has introduced the concept of default methods which allow the interfaces to have
methods with implementation without affecting the classes that implement the interface.
The most important use of default methods in interfaces is to provide additional functionality to a
given type without breaking down the implementing classes.Before java 8,if a new method was
introduced in an interface than all the implementing classes used to break.
interface TestInterface
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 23
System.out.println(a*a);
d.square(4);
interface TestInterface
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 24
System.out.println(a*a);
d.square(4);
To write sensitive code which would not want to be accessed by any class or interface
Interface sayable
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 25
s.say();
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC
Object Oriented Programming with JAVA BCS306A 26
By: Mr.Gangappa D and Mrs.Shruthi Vijay Assistant Professors, Dept of CSE, CEC