Inheritance

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

Inheritance(IS-A relationship)

-Inheritance provided a mechanism that allowed a class to inherit property of another


class.
-When a Class extends another class it inherits all non-private members including fields
and methods.
-Inheritance in Java can be best understood in terms of Parent and Child relationship, also
known as Super class(Parent) and Sub class(child) in Java language.
-Inheritance defines is-a relationship between a Super class and its Sub class. extends and
implements keywords are used to describe inheritance in Java.

Purpose of Inheritance
1. It promotes the code reusabilty i.e the same methods and variables which are
defined in a parent/super/base class can be used in the child/sub/derived class.
2. It promotes polymorphism by allowing method overriding.
Disadvantages of Inheritance
-Main disadvantage of using inheritance is that the two classes (parent and child class)
gets tightly coupled.This means that if we change code of parent class, it will affect to all
the child classes which is inheriting/deriving the parent class, and hence, it cannot be
independent of each other.
Types of Inheritance

Single level Inheritance


-When a class is extended by only one class, it is called single-level inheritance in java or
simply single inheritance.
-In other words, creating a subclass from a single superclass is called single inheritance.
-In single-level inheritance, there is only one base class and can be one derived class.
-The derived class inherits all the properties and behaviors only from a single class.
package singleLevelInheritance;
// Create a base class or superclass.
public class A
{
// Declare an instance method.
public void methodA()
{
System.out.println("Base class method");
}
}
// Declare a derived class or subclass and extends class A.
public class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
}
public class Myclass
{
public static void main(String[] args)
{
// Create an object of class B.
B obj = new B();
obj.methodA(); // methodA() of B will be called because by default, it is available in
B.
obj.methodB(); // methodB() of B will be called.
}
}

Multilevel Inheritance
-A class that is extended by a class and that class is extended by another class forming
chain inheritance is called multilevel inheritance in java.
-In multilevel inheritance, there is one base class and one derived class at one level. At
the next level, the derived class becomes the base class for the next derived class and so
on. This is as shown below in the diagram.
package multilevelInheritance;
public class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
public class Y extends X
{
public void methodY()
{
System.out.println("Class Y method");
}
}
public class Z extends Y
{
public void methodZ()
{
System.out.println("Class Z method");
}
public static void main(String[] args)
{
Z z = new Z();
z.methodX(); // Calling X grand class method.
z.methodY(); // Calling Y parent class method.
z.methodZ(); // Calling Z class local method.
}
}

Multiple Inheritance
-Deriving subclasses from more than one superclass is known as multiple inheritance in
java. In other words, when a class extends multiple classes, it is known as multiple
inheritance.
-In multiple inheritance, there can be more than one immediate super class and there can
be one or more subclasses. Java does not support multiple inheritance through class. It
supports only single inheritance through class.

-Practically, it is very rare and difficult to use in a software project because it creates
ambiguity, complexity, and confusion when a class inherits methods from two
superclasses with the same method signature. The ambiguity created by the multiple
inheritance is called diamond problem in java.
-But, the functionality of multiple inheritance in Java can be achieved by using interfaces.
When two or more interfaces are implemented by a single class, only one method can
share the method signature.
Hierarchical Inheritance
-A class that is inherited by many subclasses is known as hierarchical inheritance in java.
-In other words, when one class is extended by many subclasses, it is known as
hierarchical inheritance.
-In this kind of inheritance, one class can be a parent of many other classes. Look at the
below diagram to understand hierarchical inheritance.

-In the above diagram, class A is the parent (or base class) of all three classes B, C, and
D. That is, classes B, C, and D inherit the same class A and can share all fields, methods
of class A except private members.

package hierarchicalInheritanceEx;
public class A
{
public void msgA()
{
System.out.println("Method of class A");
}
}
public class B extends A
{
// Empty class B, inherits msgA of parent class A.

}
public class C extends A
{
// Empty class C, inherits msgA of parent class A.
}
public class D extends A
{
// Empty class D, inherits msgA of parent class A.
}
public class MyClass
{
public static void main(String[] args)
{
// Create the object of class B, class C, and class D.
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();

// Calling inherited function from the base class.


obj1.msgA();
obj2.msgA();
obj3.msgA();
}
}

Hybrid Inheritance
-A hybrid inheritance in Java is a combination of single and multiple inheritance. It can
be achieved in the same way as multiple inheritance using interfaces in Java.
-By using interfaces, we can achieve multiple as well as a hybrid inheritance in Java. But
both are not allowed in Java. Typical hybrid inheritance is shown in the below diagram.
super keyword
-In Java, super keyword is used to refer to the immediate parent class of a child class.
-In other words super keyword is used by a subclass whenever it needs to refer to its
immediate super class.
Note:
Child class referring Parent class property using super keyword
Child class referring Parent class methods using super keyword
Child class calling Parent class constructor using super keyword

class Parent
{
String name;
public void details()
{
name = "Parent";
System.out.println(name);
}
public Parent(String n)
{
name = n;
}
}
public class Child extends Parent {
String name;
public Child(String n1, String n2)
{
super(n1); //passing argument to parent class constructor
this.name = n2;
}
public void details()
{
super.name = "Parent";
super.details();
//refers to parent class member
name = "Child";
System.out.println(super.name+" and "+name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}}
Can you use both this() and super() in a Constructor?
NO, because both super() and this() must be the first statement inside a constructor.
Hence we cannot use them together.

this keyword
-In Java, this is a keyword which is used to refer to the current object of a class.
-We can refer to any member of the class. It means we can access any instance variable
and method by using this keyword.
-The main purpose of using this keyword is to solve the confusion when we have same
variable name for instance and local variables.
We can use this keyword for the following purpose.
● this keyword is used to refer to current object.
● this is always a reference to the object on which method was invoked.
● this can be used to invoke current class constructor.
● this can be passed as an argument to another method.
Example:
“this” is used to
Initialize a member of the current object.
Calling Constructor
Accessing Method
Return Current Object from a Method

class Demo
{
Double width, height, depth;
Demo (double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
Demo ()
{
// Calling constructor
this("hello");
}
Demo(String str)
{
System.out.println(str);
}
public void getName()
{
System.out.println("hi");
}
public void display()
{
this.getName();
}
public Demo display1()
{
// return current object
return this;
}
public static void main(String[] args) {
Demo d = new Demo(10,20,30);
Demo d = new Demo();
System.out.println("width = "+d.width);
System.out.println("height = "+d.height);
System.out.println("depth = "+d.depth);
d.display();
Demo d = new Demo();
Demo d1 = d.display();
d1.getName();

}
}

Aggregation (HAS-A relationship)


-Aggregation is a term which is used to refer to a one way relationship between two
objects. For example, Student class can have a reference of Address class but vice versa
does not make sense.
-In Java, aggregation represents a HAS-A relationship, which means when a class
contains reference to another class known to have aggregation.
-The HAS-A relationship is based on usage, rather than inheritance. In other words, class
A has-a relationship with class B, if class A has a reference to an instance of class B.
class Author
{
String authorName;
int age;
String place;

// Author class constructor


Author(String name, int age, String place)
{
this.authorName = name;
this.age = age;
this.place = place;
}
}

class Book
{
String name;
int price;
// author details
Author author;
Book(String n, int p, Author author)
{
this.name = n;
this.price = p;
this.author = author;
}
public static void main(String[] args) {
Author author = new Author("John", 42, "USA");
Book b = new Book("Java for Beginner", 800, author);
System.out.println("Book Name: "+b.name);
System.out.println("Book Price: "+b.price);
System.out.println("------------Author Details----------");
System.out.println("Author Name: "+b.auther.authorName);
System.out.println("Author Age: "+b.author.age);
System.out.println("Auther place: "+b.author.place);
}
}

When to use Inheritance and Aggregation?


-When you want to use some property or behaviour of any class without the requirement
of modifying it or adding more functionality to it, in such cases Aggregation is a better
option because in case of Aggregation we are just using any external class inside our
class as a variable.
-Whereas when you want to use and modify some property or behaviour of any external
class or may want to add more function on top of it, its best to use Inheritance.

You might also like