You are on page 1of 7

Chapter Three

Inheritance and Polymorphism


Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent
object.

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 parent class, and you can add
new methods and fields also.

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java?

 For Method Overriding (so runtime polymorphism can be achieved).


 For Code Reusability.

Syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}
extends keyword indicates that you are making a new class that derives from an existing class.
A class that is inherited is called a super /parent/base class.
The new class is called a subclass/child/derived class.
Types of inheritance in java
On the basis of class, there can be three types of inheritance in java.

1. Simple/single/one level inheritance


 Enables a child class to inherit behavior and properties from a single parent class.
 When a subclass is derived simply from its parent class.
 There is only a sub class and its parent class.

Example:
class college{
float salary=3000;
}
class IT extends college{
float bonous=200;
public static void main(String args[])
{
IT obj=new IT();
System.out.println("Salary is:"+obj.salary);
System.out.println("Bonous is:"+obj.bonous);
}}

2. Multilevel Inheritance

 Several classes can be declared as subclasses of the same superclass.


 One-to-one ladder system. There exists single base class, single derived class and multiple
intermediate base classes.
 Multiple classes are involved in inheritance, but one class extends only one. It is an indirect
way to implement multiple inheritance.

3. Multiple Inheritance

 There exist multiple classes and single derived class.


Java does not allow multiple inheritance as we cannot inherit the behavior and properties of two
different class in one subclass/child class.

Why multiple inheritance is not supported in java?


 To reduce complexity
 simplify the language

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B
classes have same method and you call it from child class object, there will be ambiguity to call method of
A or B class.

1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8. Public Static void main(String args[]){
9. C obj=new C();
10. obj.msg();//Now which msg() method would be invoked?
11. }}

 In java programming, multiple and hybrid inheritance is supported through interface only.
4. Hierarchical Inheritance
 One class is extended by many subclasses.
 is one-to-many relationship.
5. Hybrid Inheritance
 is the combination of single, multilevel and hierarchical inheritance.

Example:
public class A{
public static void main(String[] args){
System.out.println{"A"}
}}
class B extends A{
System.out.println{"B"}
}
class C extends A{
System.out.println{"C"}
}
class D extends B{
System.out.println{"D"}
}
class E extends B{
System.out.println{"E"};
}
class F extends C{
System.out.println{"F"}
}
class G extends C{
System.out.println{"G"}}

Use of supper keyword in java

The super keyword in java is a reference variable that is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e. referred by
super reference variable.

//super is used to refer immediate parent class instance variable.

class Vehicle{
int speed=50;
}
class Car extends Vehicle{
int speed=100; //hide super class field
void display(){
System.out.println(speed);//will print speed of car i.e 100
System.out.println(super.speed);//will print speed of Vehicle i.e 50
}
public static void main(String args[]){
Car C=new Car();
C.display();
}}

// super() is used to invoke immediate parent class constructor.

class Vehicle{
Vehicle(){
System.out.println("Vehicle Constructor ");
}}
class Car extends Vehicle{
Car(){
super();//will invoke parent class constructor
System.out.println("Car Constructor ");
}
public static void main(String args[]){
Car C=new Car();
} }

// super is used to invoke immediate parent class method.

class Person{
void message(){
System.out.println("welcome");
}}
class Student extends Person{
void message(){
System.out.println("welcome to java");
}
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
public static void main(String args[]){
Student s=new Student();
s.display();
}}
Usage of this keyword in java
In java, this is a reference variable that refers to the current object.

// this keyword can be used to refer current class instance variable.

class Student11{
int id;
String name;
Student11(int id,String name){ // Student11(int i,String n) no need of this
this.id = id;
this.name = name;
} Output
void display(){
111 Alene
System.out.println(id+" "+name); 222 Ayrak
} Without this
public static void main(String args[]){ 0 null
Student11 s1 = new Student11(111,"Alene"); 0 null
Student11 s2 = new Student11(222,"Ayrak");
s1.display();
s2.display();
}}

// this() can be used to invoke current class constructor.

class Student13{
int id;
String name;
Student13(){System.out.println("Default constructor ");}
Student13(int id,String name){
this ();//it is used to invoked current class constructor.
this.id = id; Output
this.name = name;
}
void display(){System.out.println(id+" "+name);} Default constructor
public static void main(String args[]){ Default constructor
Student13 e1 = new Student13(111,"Alene"); 111 Alene
Student13 e2 = new Student13(222,"Ayrak"); 222 Ayrak
e1.display();
e2.display();
}}

// this keyword can be used to invoke current class method (implicitly)

class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p(); // output: method is invoked
}
}

// this can be passed as an argument in the method call.

class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
} } // output: method is invoked

Use of final with Inheritance


A class can be declared final if its definition is complete and no subclasses are desired or required. A compile-time
error occurs if the name of a final class appears in the extended clause of another class declaration; this implies that a
final class can’t have any subclasses.

Final keyword prevents overriding. To disallow a method from being overridden, specify final as a modifier at the
start of its declaration. Methods declared as final can’t be overridden.

Final prevents inheritance. Sometimes, you will want to prevent a class from being inherited. To do this, precede the
class declaration with the keyword final. Declaring a class as final implicitly declares all of its methods as final too.

Constructor order dependencies


Instantiating a subclass object begins a chain of constructor calls in which the subclass constructor, before performing
its own tasks, invokes its direct superclass’s constructor (calling the superclass’s default constructor or no-argument
constructor).

Similarly, if the superclass was derived from another class, the superclass constructor would be required to invoke the
constructor of the next class up in the hierarchy, and so on. The last constructor called in the chain is always the
constructor of class Object. The original subclass constructor’s body finishes executing last.
Private Methods Are Not Inherited

Private methods are just like private variables in terms of not being directly available. But in the case of methods, the
restriction is more dramatic. A private variable can be accessed indirectly (through public methods of the class). A
private method is simply not available. It is just as if the private method were not inherited.

You might also like