Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Inheritance in Java.docx

Java inheritance types detailed file

Uploaded by

Harsh Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Inheritance in Java.docx

Java inheritance types detailed file

Uploaded by

Harsh Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Unit 2 ( Ch 1)

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
}

// use of extends keyword


// to perform inheritance
class Dog extends Animal {

// methods and fields of Animal


// methods and fields of Dog
}

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 {

// field and method of the parent class


String name;
public void eat() {
System.out.println("I can eat");
}
}

// inherit from Animal


class Dog extends Animal {

// new method in subclass


public void display() {
System.out.println("My name is " + name);
}
}

class Main {
public static void main(String[] args) {

// create an object of the subclass


Dog labrador = new Dog();

// access field of superclass


labrador.name = "Rohu";
labrador.display();

// call method of superclass


// using object of subclass
labrador.eat();

}
}
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;

protected void display() {


System.out.println("I am an animal.");
}
}

class Dog extends Animal {

public void getInfo() {


System.out.println("My name is " + 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,

Java Single Inheritance

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,

Java Multilevel Inheritance

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,

Java Hybrid Inheritance


Here, we have combined hierarchical and multiple inheritance to form a hybrid inheritance.
Java Method Overriding
if the same method is defined in both the superclass and the subclass, then the method of the
subclass class overrides the method of the superclass. This is known as method overriding.
Example 1: Method Overriding
class Animal {
public void displayInfo() {
System.out.println("I am an animal.");
}
}
class Dog extends Animal {
@Override
public void displayInfo() {
System.out.println("I am a dog.");
}
}

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.

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.
Example
1.​ //Java Program to illustrate the use of super keyword
2.​ //Creating parent class
3.​ class Animal{
4.​ String color="white";
5.​ }
6.​ //Creating child class
7.​ class Dog extends Animal{
8.​ String color="black";
9.​ void printColor(){
10.​ System.out.println(color);//prints color of Dog class
11.​ System.out.println(super.color);//prints color of Animal class
12.​ }
13.​}
14.​//Creating Main class to create object and call methods
15.​public class Main{
16.​ public static void main(String args[]){
17.​ Dog d=new Dog();
18.​ d.printColor();
19.​ }
20.​}

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.

Java Abstract Class and Abstract Methods


Java Abstract Class
The abstract class in Java cannot be instantiated (we cannot create objects of abstract
classes). We use the abstract keyword to declare an abstract class. For example,
// create an abstract class
abstract class Language {
// fields and methods
}
...

// try to create an object Language


// throws an error
Language obj = new Language();
An abstract class can have both the regular methods and abstract methods. For
example,
abstract class Language {
// abstract method
abstract void method1();

// 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.

Java Abstract Method


A method that doesn't have its body is known as an abstract method. We use the
same abstract keyword to create abstract methods. For example,
abstract void display();
Here, display() is an abstract method. The body of display() is replaced by ;.
If a class contains an abstract method, then the class should be declared abstract.
Otherwise, it will generate an error. For example,
// error
// class should be abstract
class Language {

// abstract method
abstract void method1();
}

Example: Java Abstract Class and Method


Though abstract classes cannot be instantiated, we can create subclasses from it. We
can then access members of the abstract class using the object of the subclass. For
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) {

// create an object of Main


Main obj = new Main();

// access method of abstract class


// using object of Main class
obj.display();
}
}
Run Code
Output
This is Java programming
In the above example, we have created an abstract class named Language. The class
contains a regular method display().
We have created the Main class that inherits the abstract class. Notice the statement,
obj.display();
Here, obj is the object of the child class Main. We are calling the method of the
abstract class using the object obj.

Implementing Abstract Methods


If the abstract class includes any abstract method, then all the child classes inherited
from the abstract superclass must provide the implementation of the abstract method.
For example,
abstract class Animal {
abstract void makeSound();

public void eat() {


System.out.println("I can eat.");
}
}

class Dog extends Animal {

// provide implementation of abstract method


public void makeSound() {
System.out.println("Bark bark");
}
}

class Main {
public static void main(String[] args) {

// create an object of Dog class


Dog d1 = new Dog();

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.

You might also like