Unit2 Inheritance
Unit2 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.
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 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";
}
{
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.
{
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
10
Unit 2 Inheritance
}
}
Abstract class with constructor
import java.io.*;
import java.util.*;
{
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.
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
15