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

Java_Inheritance

The document provides an overview of inheritance in Java, explaining key concepts such as subclasses, superclasses, method overriding, and the use of the 'super' keyword. It details various types of inheritance, including single, multilevel, hierarchical, multiple, and hybrid inheritance, while also discussing limitations and the diamond problem associated with multiple inheritance. Additionally, it emphasizes the importance of inheritance for code reusability and polymorphism in object-oriented programming.

Uploaded by

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

Java_Inheritance

The document provides an overview of inheritance in Java, explaining key concepts such as subclasses, superclasses, method overriding, and the use of the 'super' keyword. It details various types of inheritance, including single, multilevel, hierarchical, multiple, and hybrid inheritance, while also discussing limitations and the diamond problem associated with multiple inheritance. Additionally, it emphasizes the importance of inheritance for code reusability and polymorphism in object-oriented programming.

Uploaded by

Rishav Dev
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Java Inheritance

Introduction
• Inheritance is one of the key features of OOP that
allows us to create a new class from an existing class.
• The new class that is created is known
as subclass (child or derived class), and
• The existing class from where the child class is
derived is known as superclass (parent or base class).
• The extends keyword is used to perform inheritance
in Java. For example,

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.
Example 1: Java Inheritance
class Animal { class Main {
public static void main(String[] args) {
// field and method of the parent class
String name; // create an object of the subclass
public void eat() { Dog labrador = new Dog();
System.out.println("I can eat");
} // access field of superclass
} labrador.name = "Rohu";
labrador.display();
// inherit from Animal
class Dog extends Animal { // call method of superclass
// using object of subclass
// new method in subclass labrador.eat();
public void display() {
System.out.println("My name is " + name); }
} }
}
• In the above example, we have derived a subclass Dog from superclass Animal.
• 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.
is-a relationship:

• In Java, inheritance is an is-a relationship. That is, we use inheritance only if there
exists an is-a relationship between two classes. For example,
• Car is a Vehicle
• Orange is a Fruit
• Surgeon is a Doctor
• Dog is an Animal
• Here, Car can inherit from Vehicle, Orange can inherit from Fruit, and so on.
Method Overriding in Java Inheritance

• In Example 1, we see the object of the subclass can access the method of the
superclass.
• However, if the same method is present in both the superclass and subclass, what
will happen?
• In this case, the method in the subclass overrides the method in the superclass.
This concept is known as method overriding in Java.
class Animal { // new method in subclass
public void bark() {
// method in the superclass System.out.println("I can bark");
public void eat() { }
System.out.println("I can eat"); }
}
} class Main {
public static void main(String[] args) {
// Dog inherits Animal
class Dog extends Animal { // create an object of the subclass
Dog labrador = new Dog();
// overriding the eat() method
@Override // call the eat() method
public void eat() { labrador.eat();
System.out.println("I eat dog food"); labrador.bark();
} }
}

Note: We have used the @Override annotation to tell the compiler that we are overriding a method.
However, the annotation is not mandatory.
super Keyword in Java Inheritance
• Previously we saw that the same method in the subclass overrides the method in superclass.
• In such a situation, the super keyword is used to call the method of the parent class from the
method of the child class.
• Example 3:
class Animal {
{ class Main {
// method in the superclass
// call method of superclass public static void main(String[] args)
public void eat() {
super.eat(); {
System.out.println("I can eat");
System.out.println("I eat dog
}
food"); // create an object of the subclass
}
} Dog labrador = new Dog();
// new method in subclass
// Dog inherits Animal
public void bark() { // call the eat() method
class Dog extends Animal {
System.out.println("I can bark"); labrador.eat();
} labrador.bark();
// overriding the eat() method
} }
@Override
}
public void eat()
Contd.

• Here, the super keyword is used to call the eat() method present in the superclass.

• We can also use the super keyword to call the constructor of the superclass from
the constructor of the subclass.
Why use inheritance?
• The most important use of inheritance in Java is code reusability.
• The code that is present in the parent class can be directly used by the
child class.
• Method overriding is also known as runtime polymorphism.
• Hence, we can achieve Polymorphism in Java with the help of
inheritance.
Types of inheritance
There are five types of inheritance:

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance
1. Single Inheritance
• In single inheritance, a single subclass extends from a single
superclass.
2. Multilevel Inheritance
• In multilevel inheritance, a subclass extends from a superclass and
then the same subclass acts as a superclass for another class.
3. Hierarchical Inheritance
• In hierarchical inheritance, multiple subclasses extend from a single
superclass.
4. Multiple Inheritance
• In multiple inheritance, a single subclass extends from multiple
superclasses.
• Note: Java doesn't support multiple inheritance. However, we can achieve
multiple inheritance using interfaces.
5. Hybrid Inheritance
• Hybrid inheritance is a combination of two or more types of inheritance.
Example: Single Inheritance
class Student{
void Fee() {
System.out.println("Student Fee= 20000");
}
}
class Student_Name extends Student{
void Name() {
System.out.println("Student Name=Jayanti");
}
}
class College {
public static void main(String args[]) {
Student_Name p = new Student_Name();
p.Fee();
p.Name();
}
}
Limitations of Single Inheritance in Java
• A Child class can only inherit from a single parent Class which results
in less flexibility for class designs.
• It can limit the ability to reuse code as some code might not fit in a
hierarchy caused by the single inheritance.
• It can cause ambiguity in code or throw errors, as some inherited
methods can have the same names but have different operations.
Example: Multi-level Inheritance
Example: Hierarchal Inheritance
public class ClassH1 public class ClassH4 extends ClassH1
{ {
public void dispH1() public void dispH4()
{ {
System.out.println("disp() method of ClassH1"); System.out.println("disp() method of ClassH4");
} }
} }
public class ClassH2 extends ClassH1 public class HierarchicalInheritanceTest
{ {
public void dispH2() public static void main(String args[])
{ {
System.out.println("disp() method of ClassH2"); //Assigning ClassH2 object to ClassH2 reference
} ClassH2 h2 = new ClassH2();
} //call dispH2() method of ClassH2
public class ClassH3 extends ClassH1 h2.dispH2();
{ //call dispH1() method of ClassH1
public void dispH3() h2.dispH1();
{
System.out.println("disp() method of ClassH3");
}
}
Output:
• disp() method of ClassH2
• disp() method of ClassH1
• disp() method of ClassH3
• disp() method of ClassH1
• disp() method of ClassH4
• disp() method of ClassH1
Example: Hybrid Inheritance
Using Single and Hierarchical Inheritance in hybrid inheritance
class GrandMother public class Son extends Mother
{ {
public void showG() public void showS()
{ {
System.out.println("She is grandmother."); System.out.println("He is Son.");
} }
} public static void main(String args[])
class Mother extends GrandMother {
{ Daughter obj = new Daughter();
public void showM() obj.showD();
{ obj.showM();
System.out.println("She is mother."); obj.showG();
} Son obj2 = new Son();
} obj2.showS();
class Daughter extends Mother obj2.showM();
OUTPUT:
{ obj2.showG();
She is daughter.
public void showD() }
She is mother.
{ }
She is grandmother.
System.out.println("She is daughter.");
He is Son.
}
She is mother.
}
She is grandmother.
Which Inheritance Is Not Supported in Java?

• The Multiple inheritances using classes are not supported.


• Java only allows for single inheritance, where a class can inherit from only one
superclass to avoid the more complexities that arise from multiple inheritances.
• There are very few situations where multiple inheritances are truly needed.
• So it is recommended to avoid keeping the codebase simple and manageable.
• One of the problems with multiple inheritances is the Diamond problem.
Diamond Problem:
• Talking about Multiple inheritance is when,
• a child class inherits the properties from more than one parents and the
methods for the parents are same
(Method name and parameters are exactly the same)
• then child gets confused about which method will be called. This problem in
Java is called the Diamond problem.
Example:
// Java Program to demonstrate // Inherting the Properties from
// Diamond Problem // Both the classes
import java.io.*; class test extends Parent1, Parent2
// Parent Class1 {
class Parent1 { // main function
void fun() { public static void main(String[] args)
System.out.println("Parent1"); } {
} test t = new test();
// Parent Class2 t.fun();
class Parent2 { }
void fun() { }
System.out.println("Parent2"); }
}

Explanation : In above example we have seen that “test” class is extending two classes “Parent1 ” and
“Parent2” and its calling function “fun()” which is defined in both parent classes so now here it got confused
which definition it should inherit.
Solution of Diamond Problem:

• Although Diamond Problem is a serious issue but we can create a solution for it
which is Interface.
• Interface are created by using interface keyword.
• It contains all methods by default as abstract, we don’t need to declared as
abstract, compiler will do it implicitly.
// Java Programs to illustrate // Inheritance using Interfaces
// use of Interface to solve class test implements Parent1, Parent2 {
// Diamond Problem public void fun()
import java.io.*; {
System.out.println("fun function");
// Interfaces Declared }
interface Parent1 { }
void fun();
} // Driver Class
class test1 {
// Interfaces Declared // main function
interface Parent2 { public static void main(String[] args)
void fun(); {
} test t = new test();
t.fun();
}
}

We are able to implement multiple inheritance through interface just because in case of interface we does
not provide the definition of function and when class implement that function then it write definition of
function only once.
Inheritance: Method Overriding
Introduction:
• Inheritance is an OOP property that allows us to derive a new class
(subclass) from an existing class (superclass).
• The subclass inherits the attributes and methods of the superclass.
• Now, if the same method is defined in both the superclass and the
subclass, then the method of the subclass overrides the method of
the superclass.
• This is known as 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) { Here, the @Override annotation specifies the compiler that the
Dog d1 = new Dog(); method after this annotation overrides the method of the
d1.displayInfo(); superclass.
}
}
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.
• A common question that arises while performing overriding is:
Can we access the method of the superclass after overriding?
• Well, the answer is Yes. To access the method of the superclass from
the subclass, we use the super keyword.
Example : Use of super Keyword
class Animal {
public void displayInfo() {
System.out.println("I am an animal."); OUTPUT:
}
} I am an animal.
I am a dog.
class Dog extends Animal {
public void displayInfo() {
super.displayInfo(); Note:
System.out.println("I am a dog."); • It is important to note that constructors in Java are not
} inherited.
}
• Hence, there is no such thing as constructor overriding
class Main { in Java.
public static void main(String[] args) { • However, we can call the constructor of the superclass
Dog d1 = new Dog(); from its subclasses. For that, we use super().
d1.displayInfo();
}
}
Access Specifiers in Method Overriding
• The same method declared in the superclass and its subclasses can
have different access specifiers. However, there is a restriction
• We can only use those access specifiers in subclasses that provide
larger access than the access specifier of the superclass. For example,
• Suppose, a method myClass() in the superclass is declared protected.
• Then, the same method myClass() in the subclass can be
either public or protected, but not private.
Example: Access Specifier in Overriding
class Animal {
Output:
protected void displayInfo() {
System.out.println("I am an animal.");
I am a dog.
}
}

class Dog extends Animal { • In the above example, the subclass Dog overrides the
public void displayInfo() { method displayInfo() of the superclass Animal.
System.out.println("I am a dog."); • Whenever we call displayInfo() using the d1 (object of
}
the subclass), the method inside the subclass is
}
called.
class Main { • Notice that, the displayInfo() is declared protected in
public static void main(String[] args) { the Animal superclass.
Dog d1 = new Dog(); • The same method has the public access specifier in
d1.displayInfo(); the Dog subclass.
} • This is possible because the public provides larger
} access than the protected.
super
The super keyword in Java is used in subclasses to access
superclass members (attributes, constructors and methods)
Uses of super keyword
• To call methods of the superclass that is overridden in the subclass.
• To access attributes (fields) of the superclass if both superclass and
subclass have attributes with the same name.
• To explicitly call superclass no-arg (default) or parameterized
constructor from the subclass constructor.
• Let's understand each of these uses.
1. Access Overridden Methods of the superclass
• If methods with the same name are defined in both superclass and subclass, the
method in the subclass overrides the method in the superclass.
What if the overridden method of the superclass has to be called?
• Example : super to Call Superclass Method
public void printMessage(){
class Animal {
// this calls overriding method
// overridden method display();
public void display(){
System.out.println("I am an animal"); // this calls overridden method
} super.display();
} }
}
class Dog extends Animal {
class Main {
// overriding method public static void main(String[] args)
@Override {
public void display(){ Dog dog1 = new Dog();
System.out.println("I am a dog"); dog1.printMessage();
} }
}
2. Access Attributes of the Superclass
• Example: Access superclass attribute
class Animal {
protected String type="animal";
}

class Dog extends Animal {


public String type="mammal";
• In this example, we have defined the same
public void printType() {
System.out.println("I am a " + type);
instance field type in both the
System.out.println("I am an " + super.type); superclass Animal and the subclass Dog.
} • We then created an object dog1 of the Dog class.
}
Then, the printType() method is called using this
class Main { object.
public static void main(String[] args) { • Inside the printType() function, type refers to the
Dog dog1 = new Dog();
dog1.printType();
attribute of the subclass Dog. super.type refers to
} the attribute of the superclass Animal.
}
3. Use of super() to access superclass constructor

• As we know, when an object of a class is created, its default


constructor is automatically called.
• To explicitly call the superclass constructor from the subclass
constructor, we use super(). It's a special form of the super keyword.
• super() can be used only inside the subclass constructor and must be
the first statement.
Use of super()
class Animal { class Main
{
// default or no-arg constructor of class Animal public static void main(String[] args)
Animal() { {
System.out.println("I am an animal"); Dog dog1 = new Dog();
} }
} }
class Dog extends Animal {

// default or no-arg constructor of class Dog


Dog() {

// calling default constructor of the superclass


super();

System.out.println("I am a dog");
}
}
So, why use redundant code if the compiler
automatically invokes super()?
• It is required if the parameterized constructor (a constructor that
takes arguments) of the superclass has to be called from the subclass
constructor.
• The parameterized super() must always be the first statement in the
body of the constructor of the subclass, otherwise, we get a
compilation error.
Example: Call Parameterized Constructor Using super()
class Animal { class Dog extends Animal {

// default or no-arg constructor // default constructor


Animal() { Dog() {
System.out.println("I am an animal");
} // calling parameterized constructor of the superclass
super("Animal");
// parameterized constructor
Animal(String type) { System.out.println("I am a dog");
System.out.println("Type: "+type); }
} }
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
}
}
Note that in the above example, we explicitly called the parameterized constructor super("Animal").
The compiler does not call the default constructor of the superclass in this case.
Abstract Class and Abstract Methods
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,

• An abstract class can have both the regular methods and abstract
methods. For example,
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,
• 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.
Example: Java Abstract Class and Method
• Though abstract classes cannot be abstract class Language {
instantiated, we can create subclasses
// method of abstract class
from it. public void display() {
• We can then access members of the System.out.println("This is Java Programming");
}
abstract class using the object of the
}
subclass. 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();
}
}
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.

abstract class Animal {


abstract void makeSound(); class Main {
public static void main(String[] args) {
public void eat() {
System.out.println("I can eat."); // create an object of Dog class
} Dog d1 = new Dog();
}
d1.makeSound();
class Dog extends Animal { d1.eat();
}
// provide implementation of abstract method }
public void makeSound() {
System.out.println("Bark bark");
}
}
Accesses Constructor of Abstract Classes
• An abstract class can have constructors like the regular class. And, we can access
the constructor of an abstract class from the subclass using the super keyword
Java Abstraction
• The major use of abstract classes and methods is to achieve abstraction in
Java.
• Abstraction is an important concept of object-oriented programming that
allows us to hide unnecessary details and only show the needed information.
• This allows us to manage complexity by omitting or hiding details with a
simpler, higher-level idea.
• A practical example of abstraction can be motorbike brakes. We know what
brake does. When we apply the brake, the motorbike will stop. However,
the working of the brake is kept hidden from us.
• The major advantage of hiding the working of the brake is that now the
manufacturer can implement brake differently for different motorbikes,
however, what brake does will be the same.
abstract class MotorBike {
abstract void brake(); class Main {
} public static void main(String[] args) {
MountainBike m1 = new MountainBike();
class SportsBike extends MotorBike { m1.brake();
SportsBike s1 = new SportsBike();
// implementation of abstract method s1.brake();
public void brake() { }
System.out.println("SportsBike Brake"); }
}
}
class MountainBike extends MotorBike {

// implementation of abstract method


public void brake() {
System.out.println("MountainBike
Brake");
}
}
• In the above example, we have created an abstract super
class MotorBike.
• The superclass MotorBike has an abstract method brake().
• The brake() method cannot be implemented inside MotorBike. It is
because every bike has different implementation of brakes.
• So, all the subclasses of MotorBike would have different
implementation of brake().
• So, the implementation of brake() in MotorBike is kept hidden.
• Here, MountainBike makes its own implementation
of brake() and SportsBike makes its own implementation of brake().
Key Points to Remember
• We use the abstract keyword to create abstract classes and methods.
• An abstract method doesn't have any implementation (method body).
• A class containing abstract methods should also be abstract.
• We cannot create objects of an abstract class.
• To implement features of an abstract class, we inherit subclasses from it and create
objects of the subclass.
• A subclass must override all abstract methods of an abstract class. However, if the
subclass is declared abstract, it's not mandatory to override abstract methods.
• We can access the static attributes and methods of an abstract class using the
reference of the abstract class.
Non-Access Modifiers
• do not control access level, but provides other functionality.
• For classes, you can use either final or abstract:
Modifiers Description
final The class cannot be inherited by other classes
abstract The class cannot be used to create objects (To access an abstract
class, it must be inherited from another class.)

• For attributes and methods, you can use the one of the following:
Modifiers Description
final Attributes and methods cannot be overridden/modified
abstract Can only be used in an abstract class, and can only be used on
methods. The method does not have a body, for example abstract
void run();. The body is provided by the subclass (inherited from).
static Attributes and methods belongs to the class, rather than an object
final keyword:
• The final keyword is a non-access modifier used for classes, attributes and
methods, which makes them non-changeable (impossible to inherit or override).
• The final keyword is useful when you want a variable to always store the same
value, like PI (3.14159...).
• This is useful when you want to create immutable classes or secure a class that
should not be extended for security or design reasons.
• Example: Set a variable to final, to prevent it from being overridden/modified:
public class Main
{
final int x = 10;
public static void main(String[] args)
{
Main myObj = new Main();
myObj.x = 25; // will generate an error: cannot assign a value to a final variable
System.out.println(myObj.x);
}
}

You might also like