Module 2 - MULTIPLE INHERITANCE - LectureNotes
Module 2 - MULTIPLE INHERITANCE - LectureNotes
Inheritance – Inheritance hierarchies- super and subclasses- member access rules- super
keyword- preventing inheritance: final classes and methods- the object class and its methods
Polymorphism –dynamic binding- method overriding- abstract classes and methods
o In OOP another important feature is Reusability which is very use full in two major
issues of development :
Saving Time
Saving Memory
o In C++/Java the mechanism implements this reusability is Inheritance.
o Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
o The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
o Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
class Animal{
void eat(){
System.out.println("Eating...");
}
}
class Dog extends Animal{
void bark(){
System.out.println("Barking...");
}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output
Barking….
Eating…..
Forms of Inheretence:
1. Single Inheretence
2. Hierarichal Inherintence
3. Multiple Inherintence
4. Multilevel Inherintence
5. Hybrid Inherintence
Single Inherintence:
Derivation a subclass from only one super class is called Single Inherintence. In single inheritance, a
sub-class is derived from only one super class. It inherits the properties and behavior of a single-parent
Hierarchical Inheritance:
Derivation of several classes from a single super class is called Hierarchical Inheritance.
Example:
class Student
{
public void methodStudent()
{
System.out.println("The method of the class Student invoked.");
}
}
class Science extends Student
{
public void methodScience()
{
System.out.println("The method of the class Science invoked.");
}
}
class Commerce extends Student
{
public void methodCommerce()
{
System.out.println("The method of the class Commerce invoked.");
}
}
class Arts extends Student
{
public void methodArts()
{
System.out.println("The method of the class Arts invoked.");
}
}
public class HierarchicalInheritanceExample
{
public static void main(String args[])
{
Science sci = new Science();
Commerce comm = new Commerce();
Arts art = new Arts();
//all the sub classes can access the method of super class
sci.methodStudent();
comm.methodStudent();
art.methodStudent();
}
}
Output:
The method of the class Student invoked.
The method of the class Student invoked.
The method of the class Student invoked.
Multilevel Inheritance:
In multi-level inheritance, a class is derived from a class which is also derived from
another class is called multi-level inheritance. In simple words, we can say that a class that has
more than one parent class is called multi-level inheritance. Note that the classes must be at different
levels. Hence, there exists a single base class and single derived class but multiple intermediate
base classes.
Example:
class Student
{
int reg_no;
void getNo(int no)
{
reg_no=no;
}
void putNo()
{
System.out.println("registration number= "+reg_no);
}
}
//intermediate sub class
class Marks extends Student
{
float marks;
void getMarks(float m)
{
marks=m;
}
void putMarks()
{
System.out.println("marks= "+marks);
}
}
//derived class
class Sports extends Marks
{
float score;
void getScore(float scr)
{
score=scr;
}
void putScore()
{
System.out.println("score= "+score);
}
}
public class MultilevelInheritanceExample
{
public static void main(String args[])
{
Sports ob=new Sports();
ob.getNo(0987);
ob.putNo();
ob.getMarks(78);
ob.putMarks();
ob.getScore(68.7);
ob.putScore();
}
}
Output:
registration number= 0987
marks= 78.0
score= 68.7
But java does not support Multiple Inheritance directly. It can be implemented by using interface
concept. An interface is an abstract "class" that is used to group related methods with "empty"
bodies: To access the interface methods, the interface must be "implemented" (kinda like
inherited) by another class with the implements keyword (instead of extends).
Consider following example:
Example:
class A
{
public void execute()
{
System.out.println("Hi.. Executing From Class A");
}
}
class B
{
public void execute()
{
System.out.println("Hi.. Executing From Class B");
}
}
class C extends A, B
{
}
public class Main
{
public static void main(String[] args)
{
C obj = new C(); // creating object of class C
obj.execute(); // execute() method is present in both class A and B
}
}
The above code gives error because the compiler cannot decide which execute() method is to
be invoked. Due to this reason, Java does not support multiple inheritances at the class level but
can be achieved through an interface.
Example:
// Java program to illustrate the
// concept of Multiple inheritance using interface
interface A
{
public void execute();
}
interface B
{
public void execute();
}
class C implements A, B
{
public void execute()
{
System.out.println("Hello.. From Implementation Class!!");
}
}
public class Main
{
public static void main(String[] args)
{
C obj = new C();
obj.execute();
}
}
Example 2:
interface Backend {
// abstract class
public void connectServer();
}
class Frontend {
java.connectServer();
}
Output: Java can be used as backend language.
Java can also be used as frontend.
Hybrid Inheritance:
Derivation of a class involving more than one from on Inheritance is called Hydrid Inheritance
In general, the meaning of hybrid (mixture) is made of more than one thing. In Java, the hybrid
inheritance is the composition of two or more types of inheritance. The main purpose of using
hybrid inheritance is to modularize the code into well-defined classes. It also provides the code
reusability. The hybrid inheritance can be achieved by using the following combinations:
o Single and Multiple Inheritance (not supported but can be achieved through interface)
o Multilevel and Hierarchical Inheritance
o Hierarchical and Single Inheritance
o Multiple and Multilevel Inheritance
Example:
class HumanBody
{
public void displayHuman()
{
System.out.println("Method defined inside HumanBody class");
}
}
interface Male
{
public void show();
}
interface Female
{
public void show();
}
public class Child extends HumanBody implements Male, Female
{
public void show()
{
System.out.println("Implementation of show() method defined in interfaces Male and Female");
}
public void displayChild()
{
System.out.println("Method defined inside Child class");
}
public static void main(String args[])
{
Child obj = new Child();
System.out.println("Implementation of Hybrid Inheritance in Java");
obj.show();
obj.displayChild();
}
}
Defining a Subclass:
A subclass is defined as
Variable declaration;
Method declaration;
The keyword extends signifies that the properties of the super class name are extended to the
subclass name. The subclass will now contain its own variables and methods as well as those
of the super class. But it is not vice-versa.
o Even though a subclass includes all of the members of its super class, it cannot
accessthose members who are declared as Private in super class. ―Super clas s Reference, Sub clas s Object‖.
The super keyword in Java is a reference variable which is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable.
Usage of Java super Keyword
super can be used to refer immediate parent class instance variable.
super can be used to invoke immediate parent class method.
super() can be used to invoke immediate parent class constructor.
We can use super keyword to access the data member or field of parent class. It is used if parent class
and child class have same fields.
Example 1:
package superKeyword;
public class SuperDemo
{
// Declare an instance variable and initialize value of the variable.
int x = 100;
}
public class Sub extends SuperDemo
{
// Declare an instance variable with the same name as provided the name of an instance variable in the
superclass.
int x = 200;
void display()
{
// Call superclass variable x. But, it will call variable x of class Sub because of the same name.
System.out.println("Value of variable of Sub: " +x); // Here, we have created an object of class Sub.
// Therefore, it will print the value of the variable of the class Sub.
// To call superclass instance variable, we will use the super keyword as a reference variable.
System.out.println("Value of variable of SuperDemo: " +super.x); // x of
class SuperDemo will call.
}
public static void main(String[] args)
{
Sub s = new Sub();
s.display();
}
}
Output:
Value of variable of Sub: 200
Example 2:
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}}
Output: black
White
Example 1:
// Superclass definition
class QuadrilateralShape {
// Method to display the shape type
Example 2:
class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal{
void eat(){
System.out.println("eating bread...");
}
void bark(){
System.out.println("barking...");
}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
Output:
eating
barking
The super keyword can also be used to invoke the parent class constructor. Let's see a simple
example:
Example 1:
// Superclass definition
class Shape {
// Declare variables to store the dimensions
double dimension1, dimension2;
Example 2:
class Animal{
Animal(){System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:
animal is created
dog is created
o The second form of super acts somewhat like this keyword, except that it always refers tothe
super class of the sub class in which it is used.
o The syntax is:
o Super.member ;
o Member can either be method or an instance variable
Program
// Using super to overcome namehiding.
class A {
int i;
}
// Create a subclass by extending class A. class B extends A {
int i; // this i hides the i in AB(int a, int b) {
super.i = a; // i in A
i = b; // i in B
}
void show() {
System.out.println("i in superclass: " +
super.i);System.out.println("i in subclass: " +
i);
}
}
class UseSuper {
public static void
main(String args[]) { B
subOb = new B(1, 2);
subOb.show();
}
}
Output:
i in superclass: 1
i in subclass: 2
Always the super class constructor will be executed first and sub class constructor will beexecuted
last.
}
class CallingCons {
public static void main(String args[]) { C c = new C();
}
}
Output:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
The final keyword is a non-access modifier used for classes, attributes and methods, which makes
them non-changeable (impossible to inherit or override).
The final keyword is useful when you want a variable to always store the same value, like PI
(3.14159...). The final keyword is called a "modifier".
A variable that is declared as a final variable is a constant throughout the program and its
value cannot be changed whatsoever.
Method that is declared final cannot be overridden by any other subclasses.
A class that is declared final cannot be inherited by any other class.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Example 2:
// Example of final method
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output: Compile Time Error
Example 3:
// Example of final class
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
Output: Compile Time Error
All methods and variables can be overridden by default in a subclasses. If we need to prevent the
subclasses from overriding the members of the superclass, we can declare them final. Any attempt to
override a final method in a subclass results in the compile-time-error. Methods declared as final cannot
be overridden. The following fragment illustrates final:
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!");
}
}
Example 2:
class Parent {
final void fun() {
System.out.println("Parent Fun");
}}
Sometimes you will 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. To prevent a class from being inherited, add final to class declaration.
Declaring a class as final declares all of its methods as final.
We cannot declare a class as both abstract and final since an abstract class has to be extended by
its subclasses.
Here is an example of a final class:
final class A {
// ...
}
Polymorphism
Polymorphism in Java is the task that performs a single action in different ways.
Polymorphism occurs when there is inheritance, i.e., many classes are related. The derivation of the
word Polymorphism is from two different Greek words- poly and morphs. “Poly” means numerous,
and “Morphs” means forms. So, polymorphism means innumerable forms.
Example:
class Shapes {
public void area() {
System.out.println("The formula for area of ");
}
}
class Triangle extends Shapes {
public void area() {
System.out.println("Triangle is ½ * base * height ");
}
}
class Circle extends Shapes {
public void area() {
System.out.println("Circle is 3.14 * radius * radius ");
}
}
class Main {
public static void main(String[] args) {
Binding: Connecting a method call to the method body is known as binding . There are two types
pf binding in Java:
1. Static Binding (also known as Early Binding).
2. Dynamic Binding (also known as Late Binding).
Look at the below figure in which we have defined a class X. It has two methods m1() and
m2(). The x.m1(); (method call) is linked with m1() method whereas, x.m2(); is linked with
m2() method. This linking is called binding.
Static binding:
When type of the object is determined at compiled time (by the compiler), it is known as static
binding. If there is any private, final or static method in a class, there is static binding.
Java compiler just checks which method is going to be called through reference variable
and method definition exists or not.
This binding is also known as early binding because it takes place before the program actually
runs. An example of static binding is method overloading.
Example1:
package methodOverloading;
public class Addition
{
void add(int x, int y)
{
int sum = x + y;
System.out.println("Sum of two numbers: " +sum);
}
void add(int x, int y, int z)
{
int sum = x + y + z;
System.out.println("Sum of three numbers: " +sum);
}
public static void main(String[] args)
{
Addition a = new Addition();
a.add(10, 20); // Calling add() method with passing two argument values.
a.add(20, 30, 40); // Calling add() method with passing three argument values.
}
}
Output:
Sum of two numbers: 30
Sum of three numbers: 90
In the above preceding code, Java compiler did not check the type of object. It just checked only
method call through reference variable and method definition.
Example 2:
package MCA;
class Person
{
public void speak()
{
System.out.println("Person speaks");
}
}
class Teacher extends Person
{
From the above code, we got the same output from the parent class. This happened because:
The reference for the parent class and the child class is the same(Person). That is, a single
object refers to both of them.
Since the method is static, the compiler is aware that this method can not be overridden in the
child class and it knows which method to call. Therefore there is no ambiguity and the output
is the same for both cases.
Dynamic binding:
The binding which occurs during runtime is called dynamic binding in java. This binding is
resolved based on the type of object at runtime. In dynamic binding, the actual object is used for
binding at runtime.
Dynamic binding is also called late binding or runtime binding because binding occurs during
runtime. An example of dynamic binding is method overriding.
Let’s take an example program based on dynamic binding in Java.
Example 1:
package dynamicBinding;
public class Animal
{
void eat()
{
System.out.println("Animals eat both plants and flesh");
}
}
public class Lion extends Animal
{
void eat()
{
System.out.println("Lions eat flesh because they are carnivore");
}
}
public class DynamicBindingTest
{
public static void main(String[] args)
{
Animal a = new Animal();
a.eat(); // It will call eat() method of Animal class because the reference variable is pointing to
object of animal class.
Animal a1 = new Lion();
a1.eat(); // It will call eat() method of Lion class because the reference variable is pointing
towards the object of Loin class.
}
}
Output:
Animals eat both plants and flesh
Lions eat flesh because they are carnivore
Example 2:
package MCA;
class Person
{
public void speak()
{
System.out.println("Person speaks");
}
}
class Teacher extends Person
{
@Override
public void speak()
{
System.out.println("Teacher speaks");
}
}
public class DynamicBinding
{
public static void main( String args[])
{
//Reference and objects are of Person type.
Person obj2 = new Person();
obj2.speak();
// Reference is of Person type and object is Teacher type
Person obj = new Teacher();
obj.speak();
}
}
Output:
Person speaks
Teacher speaks
Method overriding:
In a class hierarchy, when a method in a sub class has the same name and type signature as a
method in its super class, then the method in the sub class is said to be override the method in
the sub class.
When an overridden method is called from within a sub class, it will always refers to the version
of that method defined by the sub class.
The version of the method defined in the super class is hidden.
In this situation, first it checks the method is existed in super class are not. If it is existed then
it executes the version of sub class otherwise it gives no such method foundexception.
Example:
class Human{
//Overridden method
public void eat()
{
System.out.println("Human is eating");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println("Boy is eating");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
}
Dynamic method dispatch
Method Overriding is an example of runtime polymorphism. When a parent class reference
points to the child class object then the call to the overridden method is determined at runtime,
because during method call which method(parent class or child class) is to be executed is
determined by the type of object. This process in which call to the overridden method is resolved
at runtime is known as dynamic method dispatch. Lets see an example to understand this:
Example:
class ABC{
//Overridden method
public void disp()
{
System.out.println("disp() method of parent class");
}
}
class Demo extends ABC{
//Overriding method
public void disp(){
System.out.println("disp() method of Child class");
}
public void newMethod(){
System.out.println("new method of child class");
}
public static void main( String args[]) {
/* When Parent class reference refers to the parent class object
* then in this case overridden method (the method of parent class)
* is called.
*/
ABC obj = new ABC();
obj.disp(); /* When parent class reference refers to the child class object
* then the overriding method (method of child class) is called.
* This is called dynamic method dispatch and runtime polymorphism
*/
ABC obj2 = new Demo();
obj2.disp();
}
}
Output:
disp() method of parent class
disp() method of Child class
Example:
abstract class Language {
// method of abstract class
public void display() {
System.out.println("This is Java Programming");
}
}
class Main extends Language {
public static void main(String[] args) {
Main obj = new Main();
Example 2:
abstract class Multiply {
// abstract methods
// sub class must implement these methods
public abstract int MultiplyTwo (int n1, int n2);
public abstract int MultiplyThree (int n1, int n2, int n3);
// if the abstract methods are not implemented, compiler will give an error
public int MultiplyTwo (int num1, int num2) {
return num1 * num2;
}
public int MultiplyThree (int num1, int num2, int num3) {
return num1 * num2 * num3;
}
// main method
public static void main (String args[]) {
Multiply obj = new AbstractMethodEx1();
System.out.println ("Multiplication of 2 numbers: " + obj.MultiplyTwo (10, 50));
System.out.println ("Multiplication of 3 numbers: " + obj.MultiplyThree (5, 8, 10));
obj.show();
}
}
Output:
Multiplication of 2 numbers: 500
Multiplication of 3 numbers: 400
Method of abstract class Multiply