Inheritance in Java.docx
Inheritance in Java.docx
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 based on 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.
Why Do We Need Java Inheritance?
● Code Reusability: The code written in the Superclass is common to all subclasses.
Child classes can directly use the parent class code.
● Method Overriding: Method Overriding is achievable only through Inheritance. It is
one of the ways by which Java achieves Run Time Polymorphism.
● Abstraction: The concept of abstract where we do not have to provide all details, is
achieved through inheritance. Abstraction only shows the functionality to the user.
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.
How to Use Inheritance in Java?
The extends keyword is used for inheritance in Java. Using the extends keyword indicates
you are derived from an existing class. In other words, “extends” refers to increased
functionality.
Syntax :
class DerivedClass extends BaseClass
{
//methods and fields
}
The extends keyword is used to perform inheritance in Java. For example
class Animal {
// methods and fields
}
In the above example, the Dog class is created by inheriting the methods and fields from
the Animal class.
Here, Dog is the subclass and Animal is the superclass.
class Animal {
class Main {
public static void main(String[] args) {
}
}
Output
My name is Rohu
I can eat
In the above example, we have derived a subclass Dog from superclass Animal. Notice the
statements,
labrador.name = "Rohu";
labrador.eat();
Here, labrador is an object of Dog. However, name and eat() are the members of
the Animal class.
Since Dog inherits the field and method from Animal, we are able to access the field and
method using the object of the Dog.
protected Members in Inheritance
In Java, if a class includes protected fields and methods, then these fields and methods are
accessible from the subclass of the class.
Example 4: protected Members in Inheritance
class Animal {
protected String name;
class Main {
public static void main(String[] args) {
// create an object of the subclass
Dog labrador = new Dog();
// access protected field and method
// using the object of subclass
labrador.name = "Rocky";
labrador.display();
labrador.getInfo();
}
}
Output
I am an animal.
My name is Rocky
In the above example, we have created a class named Animal. The class includes a protected
field: name and a method: display().
We have inherited the Dog class inherits Animal. Notice the statement,
labrador.name = "Rocky";
labrador.display();
Here, we are able to access the protected field and method of the superclass using
the labrador object of the subclass.
Types of inheritance
There are five types of inheritance.
1. Single Inheritance
In single inheritance, a single subclass extends from a single superclass. For example,
2. Multilevel Inheritance
In multilevel inheritance, a subclass extends from a superclass and then the same subclass
acts as a superclass for another class. For example,
3. Hierarchical Inheritance
In hierarchical inheritance, multiple subclasses extend from a single superclass. For example,
Multiple Inheritance
In multiple inheritance, a single subclass extends from multiple superclasses. For example,
Java Multiple Inheritance
Note: Java doesn't support multiple inheritance. However, we can achieve multiple
inheritance using interfaces. To learn more, visit Java implements multiple inheritance.
5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of inheritance. For example,
class Main {
public static void main(String[] args) {
Dog d1 = new Dog();
d1.displayInfo();
}
}
Output:
I am a dog.
In the above program, the displayInfo() method is present in both the Animal superclass and
the Dog subclass.
When we call displayInfo() using the d1 object (object of the subclass), the method inside the
subclass Dog is called. The displayInfo() method of the subclass overrides the same method
of the superclass.
Notice the use of the @Override annotation in our example. In Java, annotations are the
metadata that we used to provide information to the compiler. Here,
the @Override annotation specifies the compiler that the method after this annotation
overrides the method of the superclass.
It is not mandatory to use @Override. However, when we use this, the method should follow
all the rules of overriding. Otherwise, the compiler will generate an error.
Java Overriding Rules
● Both the superclass and the subclass must have the same method name, the same
return type and the same parameter list.
● We cannot override the method declared as final and static.
● We should always override abstract methods of the superclass (will be discussed in
later tutorials).
Java super
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.
Output:
black
white
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.
Example
1. //Java Program to illustrate the use of super()
2. //Creating parent class
3. class Animal{
4. void eat(){System.out.println("eating...");}
5. }
6. //Creating child class
7. class Dog extends Animal{
8. void eat(){System.out.println("eating bread...");}
9. void bark(){System.out.println("barking...");}
10. void work(){
11. super.eat();
12. bark();
13. }
14.}
15.//Creating Main class to create object and call methods
16.public class Main{
17. public static void main(String args[]){
18. Dog d=new Dog();
19. d.work();
20. }
21.}
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given
to local.
To call the parent class method, we need to use super keyword.
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:
Example
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super(); //calls the constructor of parent class
7. System.out.println("dog is created");
8. }
9. }
10.public class Main{
11. public static void main(String args[]){
12. Dog d=new Dog();
13. }
14.}
Compile and Run
Output:
animal is created
dog is created
Note: super() is added in each class constructor automatically by compiler if there is no
super() or this().
As we know well that default constructor is provided by compiler automatically if there is no
constructor. But, it also adds super() as the first statement.
Another example of super keyword where super() is provided by the compiler implicitly.
Example
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. System.out.println("dog is created");
7. }
8. }
9. public class Main{
10. public static void main(String args[]){
11. Dog d=new Dog();
12. }
13.}
Output:
animal is created
dog is created
In the above example, Animal and Dog both classes have a common property color. If we
print color property, it will print the color of current class by default. To access the parent
property, we need to use super keyword.
// regular method
void method2() {
System.out.println("This is regular method");
}
}
To know about the non-abstract methods, visit Java methods. Here, we will learn
about abstract methods.
// abstract method
abstract void method1();
}
class Main {
public static void main(String[] args) {
d1.makeSound();
d1.eat();
}
}
Run Code
Output
Bark bark
I can eat.
In the above example, we have created an abstract class Animal. The class contains an
abstract method makeSound() and a non-abstract method eat().
We have inherited a subclass Dog from the superclass Animal. Here, the
subclass Dog provides the implementation for the abstract method makeSound().
We then used the object d1 of the Dog class to call methods makeSound() and eat().
Note: If the Dog class doesn't provide the implementation of the abstract
method makeSound(), Dog should also be declared as abstract. This is because the
subclass Dog inherits makeSound() from Animal.