You are on page 1of 15

Unit 2 Inheritance

Inheritance in Java
Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). 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 from existing ones. A class that inherits from another class
can reuse the methods and fields of that class. In addition, you can add new
fields and methods to your current class as well.
Important Terminologies Used in Java Inheritance
 Class: Class is a set of objects which shares common characteristics/ behavior
and common properties/ attributes. Class is not a real-world entity. It is just a
template or blueprint or prototype from which objects are created.
 Super Class/Parent Class: The class whose features are inherited is known
as a superclass(or a base class or a parent class).
 Sub Class/Child Class: The class that inherits the other class is known as a
subclass(or a derived class, extended class, or child class). The subclass can
add its own fields and methods in addition to the superclass fields and
methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we
want to create a new class and there is already a class that includes some of
the code that we want, we can derive our new class from the existing class. By
doing this, we are reusing the fields and methods of the existing class.

Java Inheritance Types


Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance

1
Unit 2 Inheritance

1. Single Inheritance
In single inheritance, subclasses inherit the features of one superclass. In the
image below, class A serves as a base class for the derived class B.
import java.io.*;
import java.util.*;
class vechile
{
String cname;
Scanner s= new Scanner(System.in);
public void get_name()
{
System.out.println("Enter the company name");
cname=s.nextLine();
}
}
class two_wheel extends vechile
{
int avg;
Scanner s= new Scanner(System.in);
public void get_model()
{
System.out.println("Enter the avg of two wheeler");
avg=s.nextInt();
System.out.println("Company Name is "+cname);
System.out.println("Average is " +avg);
}
}
class test_single
{
public static void main(String args[] )
{
two_wheel t= new two_wheel();
t.get_name();
t.get_model();
}
}
2
Unit 2 Inheritance

Program 2
import java.io.*;
import java.util.*;
class vechile
{
String cname="Hero";
}
class two_wheel extends vechile
{
int avg=56;
public void display()
{
System.out.println("Company name is "+cname);
System.out.println("Average is " +avg);
}
}
class test_single1
{
public static void main(String args[] )
{
two_wheel t= new two_wheel();
t.display();
}
}
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well
as the derived class also acts as the base class for other classes. In the below image,
class A serves as a base class for the derived class B, which in turn serves as a base
class for the derived class C. In Java, a class cannot directly access
the grandparent’s members.
import java.io.*;
import java.util.*;

class vechile
{
String cname="Hero";
}

class two_wheel extends vechile


{
int avg=56;
public void display()
{
System.out.println("Company name is "+cname);
3
Unit 2 Inheritance

System.out.println("Average is " +avg);


}
}
class bike extends two_wheel
{
String model="shiny";
public void show()
{
System.out.println("Model is "+model);
}
}

class test_multi
{
public static void main(String args[] )
{
bike b= new bike();
b.display();
b.show();
}
}
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.
import java.io.*;
import java.util.*;
class vechile
{
String cname="Hero";
}

class two_wheel extends vechile


{
int avg=56;
String gear_type="Non Gear";
public void display()
{
System.out.println("Company name is "+cname);
System.out.println("Average is " +avg);
System.out.println("Gear type is " +gear_type);
}
}
class four_wheel extends vechile
4
Unit 2 Inheritance

{
int capacity=5;
int avg=56;
String gear_type="Auto";
public void display()
{
System.out.println("Company name is "+cname);
System.out.println("Capacity is " +capacity);
System.out.println("Average is " +avg);
System.out.println("Gear type is " +gear_type);
}
}
class bike extends two_wheel
{
String model="shiny";
public void show()
{
System.out.println("Model is "+model);
}
}

class test_hier
{
public static void main(String args[] )
{
four_wheel f= new four_wheel();
System.out.println("call from four wheeler class");
f.display();
bike b= new bike();
System.out.println("call from four bike class");
b.display();
b.show();
}
}
4. Multiple Inheritance (Through Interfaces)
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.To reduce the complexity and simplify the language, multiple inheritance is not
supported in javaConsider a scenario where A, B, and C are three classes. The C
class inherits A and B classes. If A and B classes have the same method and you call
it from child class object, there will be ambiguity to call the method of A or B class.

5
Unit 2 Inheritance

Since compile-time errors are better than runtime errors, Java renders compile-
time error if you inherit 2 classes. So whether you have same method or different,
there will be compile time error.

5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t
support multiple inheritances with classes, hybrid inheritance involving multiple
inheritance is also not possible with classes. In Java, we can achieve hybrid
inheritance only through Interfaces if we want to involve multiple inheritance to
implement Hybrid inheritance.However, it is important to note that Hybrid
inheritance does not necessarily require the use of Multiple Inheritance
exclusively. It can be achieved through a combination of Multilevel Inheritance
and Hierarchical Inheritance with classes, Hierarchical and Single Inheritance
with classes. Therefore, it is indeed possible to implement Hybrid inheritance
using classes alone, without relying on multiple inheritance type.

Super Keyword in Java


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
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
1) super is used to refer immediate parent class instance variable.
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.
import java.io.*;
class Human
{
int uid=7767676;
}
class Emp extends Human
{
int uid=34545454;
public void show_data()
{
System.out.println("Human class addhar number is " +super.uid);
System.out.println("Emp class addhar number is " +uid);
}
}
class TestSuper
6
Unit 2 Inheritance

{
public static void main(String args[])
{
Emp e= new Emp();
e.show_data();
}
}
2) super can be used to invoke parent class method
The super keyword can also be used to invoke parent class method. It should be
used if subclass contains the same method as parent class. In other words, it is used
if method is overridden.
import java.io.*;
import java.util.*;
class vechile
{
String cname="Hero";
public void display()
{
System.out.println("Company name is "+cname);

}
}
class two_wheel extends vechile
{
int avg=50;
public void display()
{
super.display();
System.out.println("Average is " +avg);
}
}
class TestMethod
{
public static void main(String args[] )
{
two_wheel t= new two_wheel();
t.display();
}
}
3) super is used to invoke parent class constructor.
The super keyword can also be used to invoke the parent class constructor. Let's
see a simple example:
import java.io.*;
import java.util.*;
7
Unit 2 Inheritance

class A
{
int p;
A(int a)
{
p=a;
}
}

class B extends A
{
int q;
B(int a,int b)
{
super(a);
q=b;
}
public void display()
{
System.out.println("Numer p is " +this.p);
System.out.println("Numer q is " +q);
System.out.println("Addition of 2 numer is " +(p+q));
}
}
class TestConst
{
public static void main(String args[] )
{
B b1= new B(10,20);
b1.display();
}
Method Overriding in Java
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in java.
Usage of Java Method Overriding
 Method overriding is used to provide specific implementation of a method
that is already provided by its super class.
 Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

8
Unit 2 Inheritance

Example of method overriding


Class Vehicle
{
void run()
{
System.out.println("Vehicle is running");
}
}
class Bike2 extends Vehicle
{
void run()
{
System.out.println("Bike is running safely");
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
obj.run();
}
}
Program2:
class Bank
{
int getRateOfInterest()
{return 0;}
}
class SBI extends Bank
{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank
{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank
{
int getRateOfInterest(){return 9;}
}
class Test2
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
9
Unit 2 Inheritance

AXIS a=new AXIS();


System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICIRateofInterest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Abstract class in Java
A class which is declared with the abstract keyword is known as an abstract class
in Java. It can have abstract and non-abstract methods (method with the body).
Before learning the Java abstract class, let's understand the abstraction in Java first.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
Another way, it shows only essential things to the user and hides the internal
details, for example, sending SMS where you type the text and send the message.
You don't know the internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
1. Abstract class (0 to 100%)
2. Interface (100%)
Abstract class in Java
A class which is declared as abstract is known as an abstract class. It can have
abstract and non-abstract methods. It needs to be extended and its method
implemented. It cannot be instantiated.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body
of the method.
Abstract Method in Java
A method which is declared as abstract and does not have implementation is known
as an abstract method.
import java.io.*;
import java.util.*;
abstract class Shapes
{
abstract void draw();
}

10
Unit 2 Inheritance

class Square extends Shapes


{
int a;
Square(int p)
{
a=p;
}
public void draw()
{
int area;
area=a*a;
System.out.println("Area of square is " +area);
}
}
class TestAbst
{
public static void main(String args[])
{
Shapes obj=new Square(15);
obj.draw();
}
}

Abstract class with non abstract method


import java.io.*;
import java.util.*;

abstract class Shapes


{
abstract void draw();
public void show()
{
System.out.println("Call from Shapes class in show");
}
}
class Square extends Shapes
{
int a;
Square(int p)
{
a=p;
}
11
Unit 2 Inheritance

public void draw()


{
int area;
area=a*a;
System.out.println("Area of square is " +area);
}
}
class TestAbst
{
public static void main(String args[])
{
Shapes obj=new Square(15);
//Shapes s= new Shapes();
obj.show();
obj.draw();

}
}
Abstract class with constructor
import java.io.*;
import java.util.*;

abstract class Shapes


{
int p;
abstract void draw();
Shapes(int a)
{
p=a;
}
public void show()
{
System.out.println("Call from Shapes class in show");
}
}

class Triangle extends Shapes


{
int q;
Triangle(int a,int b)
12
Unit 2 Inheritance

{
super(a);
q=b;

}
public void draw()
{
double area;
area=(0.5)*(p)*(q);
System.out.println("Area of square is " +area);
}
}

class TestAbst
{
public static void main(String args[])
{
Shapes obj=new Triangle(10,20);

obj.show();
obj.draw();

}
}
Final Keyword In Java
The final keyword in java is used to restrict the user. The java final keyword can
be used in many context. Final can be:
1. variable
2. method
3. class
Once any entity (variable, method or class) is declared final it can be assigned only
once. That is,
 the final variable cannot be reinitialized with another value
 the final method cannot be overridden
 the final class cannot be extended
1. Java final Variable
In Java, we cannot change the value of a final variable. For example,
class Main
{
public static void main(String[] args)

13
Unit 2 Inheritance

{
final int AGE = 32;
// try to change the final variable
AGE = 45;
System.out.println("Age: " + AGE);
}
}
In the above program, we have created a final variable named age. And we have
tried to change the value of the final variable.When we run the program, we will
get a compilation error.

2.Java final Method


Before you learn about final methods and final classes, make sure you know about
the Java Inheritance.
In Java, the final method cannot be overridden by the child class. For example,

class FinalDemo
{
// create a final method
public final void display()
{
System.out.println("This is a final method.");
}
}
class Mains extends FinalDemo
{
public final void display()
{
System.out.println("The final method is overridden.");
}
public static void main(String[] args)
{
Mains obj = new Mains();
obj.display();
}
}
In the above example, we have created a final method named display() inside
the FinalDemo class. Here, the Main class inherits the FinalDemo class.
We have tried to override the final method in the Main class. When we run the
program, we will get a compilation error with the following message.
display() in Main cannot override display() in FinalDemo
14
Unit 2 Inheritance

public final void display() {


^
overridden method is final

3. Java final Class


In Java, the final class cannot be inherited by another class. For example,
// create a final class
final class FinalClass
{
public void display()
{
System.out.println("This is a final method.");
}
}
class Main extends FinalClass
{
public void display()
{
System.out.println("The final method is overridden.");
}
public static void main(String[] args)
{
Main obj = new Main();
obj.display();
}
}
In the above example, we have created a final class named FinalClass. Here, we
have tried to inherit the final class by the Main class.
When we run the program, we will get a compilation error with the following
message.
cannot inherit from final FinalClass
class Main extends FinalClass {
^

15

You might also like