Вы находитесь на странице: 1из 24

Inheritance can be defined as the process where one class acquires the

properties (methods and fields) of another. With the use of inheritance the
information is made manageable in a hierarchical order.

The class which inherits the properties of other is known as subclass


(derived class, child class) and the class whose properties are inherited is
known as superclass (base class, parent class).

extends Keyword
extends is the keyword used to inherit the properties of a class. Following
is the syntax of extends keyword.

Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

class Calculation {

int z;

public void addition(int x, int y) {

z = x + y;

System.out.println("The sum of the given numbers:"+z);

public void Subtraction(int x, int y) {

z = x - y;

System.out.println("The difference between the given numbers:"+z);

}
public class My_Calculation extends Calculation {

public void multiplication(int x, int y) {

z = x * y;

System.out.println("The product of the given numbers:"+z);

public static void main(String args[]) {

int a = 20, b = 10;

My_Calculation demo = new My_Calculation();

demo.addition(a, b);

demo.Subtraction(a, b);

demo.multiplication(a, b);

Compile and execute the above code as shown below.


javac My_Calculation.java
java My_Calculation

After executing the program, it will produce the following result −

Output
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

In the given program, when an object to My_Calculation class is created,


a copy of the contents of the superclass is made within it. That is why,
using the object of the subclass you can access the members of a
superclass.
The Superclass reference variable can hold the subclass object, but using
that variable you can access only the members of the superclass, so to
access the members of both classes it is recommended to always create
reference variable to the subclass.

If you consider the above program, you can instantiate the class as given
below. But using the superclass reference variable ( cal in this case) you
cannot call the method multiplication(), which belongs to the subclass
My_Calculation.

Calculation cal = new My_Calculation();

demo.addition(a, b);

demo.Subtraction(a, b);

Note − A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they are not
inherited by subclasses, but the constructor of the superclass can be
invoked from the subclass.

The super keyword


The super keyword is similar to this keyword. Following are the scenarios
where the super keyword is used

 It is used to differentiate the members of superclass from the members of


subclass, if they have same names.

 It is used to invoke the superclass constructor from subclass.

Differentiating the Members


If a class is inheriting the properties of another class. And if the members of
the superclass have the names same as the sub class, to differentiate these
variables we use super keyword as shown below.
super.variable
super.method();

Sample Code
This section provides you a program that demonstrates the usage of
the super keyword.

In the given program, you have two classes


namely Sub_class and Super_class, both have a method named display()
with different implementations, and a variable named num with different
values. We are invoking display() method of both classes and printing the
value of the variable num of both classes. Here you can observe that we
have used super keyword to differentiate the members of superclass from
subclass.

Copy and paste the program in a file with name Sub_class.java.

Example
Live Demo

class Super_class {

int num = 20;

// display method of superclass

public void display() {

System.out.println("This is the display method of superclass");

public class Sub_class extends Super_class {

int num = 10;


// display method of sub class

public void display() {

System.out.println("This is the display method of subclass");

public void my_method() {

// Instantiating subclass

Sub_class sub = new Sub_class();

// Invoking the display() method of sub class

sub.display();

// Invoking the display() method of superclass

super.display();

// printing the value of variable num of subclass

System.out.println("value of the variable named num in sub class:"+ sub.num);

// printing the value of variable num of superclass

System.out.println("value of the variable named num in super class:"+


super.num);

public static void main(String args[]) {

Sub_class obj = new Sub_class();

obj.my_method();

}
Compile and execute the above code using the following syntax.
javac Super_Demo
java Super

On executing the program, you will get the following result −

Output
This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20

Invoking Superclass Constructor


If a class is inheriting the properties of another class, the subclass
automatically acquires the default constructor of the superclass. But if you
want to call a parameterized constructor of the superclass, you need to use
the super keyword as shown below.
super(values);

Sample Code
The program given in this section demonstrates how to use the super
keyword to invoke the parametrized constructor of the superclass. This
program contains a superclass and a subclass, where the superclass
contains a parameterized constructor which accepts a integer value, and we
used the super keyword to invoke the parameterized constructor of the
superclass.

Copy and paste the following program in a file with the name Subclass.java

Example
Live Demo

class Superclass {

int age;

Superclass(int age) {

this.age = age;

}
public void getAge() {

System.out.println("The value of the variable named age in super class is: "
+age);

public class Subclass extends Superclass {

Subclass(int age) {

super(age);

public static void main(String argd[]) {

Subclass s = new Subclass(24);

s.getAge();

Compile and execute the above code using the following syntax.
javac Subclass
java Subclass

On executing the program, you will get the following result −

Output
The value of the variable named age in super class is: 24

IS-A Relationship
IS-A is a way of saying: This object is a type of that object. Let us see how
the extends keyword is used to achieve inheritance.

public class Animal {

}
public class Mammal extends Animal {

public class Reptile extends Animal {

public class Dog extends Mammal {

Now, based on the above example, in Object-Oriented terms, the following


are true −

 Animal is the superclass of Mammal class.

 Animal is the superclass of Reptile class.

 Mammal and Reptile are subclasses of Animal class.

 Dog is the subclass of both Mammal and Animal classes.

Now, if we consider the IS-A relationship, we can say −

 Mammal IS-A Animal

 Reptile IS-A Animal

 Dog IS-A Mammal

 Hence: Dog IS-A Animal as well

With the use of the extends keyword, the subclasses will be able to inherit
all the properties of the superclass except for the private properties of the
superclass.

We can assure that Mammal is actually an Animal with the use of the
instance operator.

Example
Live Demo

class Animal {
}

class Mammal extends Animal {

class Reptile extends Animal {

public class Dog extends Mammal {

public static void main(String args[]) {

Animal a = new Animal();

Mammal m = new Mammal();

Dog d = new Dog();

System.out.println(m instanceof Animal);

System.out.println(d instanceof Mammal);

System.out.println(d instanceof Animal);

This will produce the following result −

Output
true
true
true

Since we have a good understanding of the extends keyword, let us look


into how the implements keyword is used to get the IS-A relationship.

Generally, the implements keyword is used with classes to inherit the


properties of an interface. Interfaces can never be extended by a class.
Example

public interface Animal {

public class Mammal implements Animal {

public class Dog extends Mammal {

The instanceof Keyword


Let us use the instanceof operator to check determine whether Mammal is
actually an Animal, and dog is actually an Animal.

Example
Live Demo

interface Animal{}

class Mammal implements Animal{}

public class Dog extends Mammal {

public static void main(String args[]) {

Mammal m = new Mammal();

Dog d = new Dog();

System.out.println(m instanceof Animal);

System.out.println(d instanceof Mammal);

System.out.println(d instanceof Animal);

}
}

This will produce the following result −

Output
true
true
true

HAS-A relationship
These relationships are mainly based on the usage. This determines
whether a certain class HAS-A certain thing. This relationship helps to
reduce duplication of code as well as bugs.

Lets look into an example −

Example

public class Vehicle{}

public class Speed{}

public class Van extends Vehicle {

private Speed sp;

This shows that class Van HAS-A Speed. By having a separate class for
Speed, we do not have to put the entire code that belongs to speed inside
the Van class, which makes it possible to reuse the Speed class in multiple
applications.

In Object-Oriented feature, the users do not need to bother about which


object is doing the real work. To achieve this, the Van class hides the
implementation details from the users of the Van class. So, basically what
happens is the users would ask the Van class to do a certain action and the
Van class will either do the work by itself or ask another class to perform
the action.

Types of Inheritance
There are various types of inheritance as demonstrated below.

A very important fact to remember is that Java does not support multiple
inheritance. This means that a class cannot extend more than one class.
Therefore following is illegal −

Example

public class extends Animal, Mammal{}

However, a class can implement one or more interfaces, which has helped
Java get rid of the impossibility of multiple inheritance

Types of inheritance
To learn types of inheritance in detail, refer: Types of Inheritance in Java.
Single Inheritance: refers to a child and parent class relationship where a class
extends the another class.

Multilevel inheritance: refers to a child and parent class relationship where a


class extends the child class. For example class C extends class B and class B
extends class A.

Hierarchical inheritance: refers to a child and parent class relationship where


more than one classes extends the same class. For example, classes B, C & D
extends the same class A.

Multiple Inheritance: refers to the concept of one class extending more than
one classes, which means a child class has two parent classes. For example
class C extends both classes A and B. Java doesn’t support multiple inheritance,
read more about it here.

Hybrid inheritance: Combination of more than one types of inheritance in a single


program. For example class A & B extends class C and another class D extends
class A then this is a hybrid inheritance example because it is a combination of
single and hierarchical inheritance.
Understanding the real scenario of abstract class

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by others i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by programmer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In real scenario, object is provided through method e.g. getShape
() method
15. s.draw();
16. }
17. }

Another exmple
1. abstract class Bank{
2. abstract int getRateOfInterest();
3. }
4. class SBI extends Bank{
5. int getRateOfInterest(){return 7;}
6. }
7. class PNB extends Bank{
8. int getRateOfInterest(){return 8;}
9. }
10.
11. class TestBank{
12. public static void main(String args[]){
13. Bank b;
14. b=new SBI();
15. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
16. b=new PNB();
17. System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
18. }}

Abstract class having constructor, data member,


methods etc.
An abstract class can have data member, abstract method, method body, constructor and
even main() method.

1. abstract class Bike{


2. Bike(){System.out.println("bike is created");}
3. abstract void run();
4. void changeGear(){System.out.println("gear changed");}
5. }
6.
7. class Honda extends Bike{
8. void run(){System.out.println("running safely..");}
9. }
10. class TestAbstraction2{
11. public static void main(String args[]){
12. Bike obj = new Honda();
13. obj.run();
14. obj.changeGear();
15. }
16. }

below pgm error:

Rule: If there is any abstract method in a class, that class must be abstract.
class Bike12
{
abstract void run();
}

An interface in java is a blueprint of a class. It has static constants and abstract methods.

The interface in java is a mechanism to achieve abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and
multiple inheritance in Java.

Java Interface also represents IS-A relationship.

It cannot be instantiated just like abstract class.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.

o By interface, we can support the functionality of multiple inheritance.

o It can be used to achieve loose coupling.


o Java 8 Interface Improvement
o Since Java 8, interface can have default and static methods which is discussed later.

o Internal addition by compiler


o The java compiler adds public and abstract keywords before the interface method.
More, it adds public, static and final keywords before data members.

o In other words, Interface fields are public, static and final by default, and methods
are public and abstract.

Understanding relationship between classes and


interfaces
As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.

Interface to interface ---extends


class to interface ---implements
class to class-------extends

Java Interface Example


In this example, Printable interface has only one method, its implementation is provided in
the A class.

1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11. }

Java Interface Example: Drawable


In this example, Drawable interface has only one method. Its implementation is provided by
Rectangle and Circle classes. In real scenario, interface is defined by someone but
implementation is provided by different implementation providers. And, it is used by
someone else. The implementation part is hidden by the user which uses the interface.

File: TestInterface1.java

1. //Interface declaration: by first user


2. interface Drawable{
3. void draw();
4. }
5. //Implementation: by second user
6. class Rectangle implements Drawable{
7. public void draw(){System.out.println("drawing rectangle");}
8. }
9. class Circle implements Drawable{
10. public void draw(){System.out.println("drawing circle");}
11. }
12. //Using interface: by third user
13. class TestInterface1{
14. public static void main(String args[]){
15. Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable
()
16. d.draw();
17. }}

Java Interface Example: Bank


Let's see another example of java interface which provides the implementation of Bank
interface.

File: TestInterface2.java

1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}

Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.
known as multiple inheritance.
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. A7 obj = new A7();
13. obj.print();
14. obj.show();
15. }
16. }

Q) Multiple inheritance is not supported through class in java but it


is possible by interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in
case of class because of ambiguity. But it is supported in case of interface because there is
no ambiguity as implementation is provided by the implementation class. For example:

1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void print();
6. }
7.
8. class TestInterface3 implements Printable, Showable{
9. public void print(){System.out.println("Hello");}
10. public static void main(String args[]){
11. TestInterface3 obj = new TestInterface3();
12. obj.print();
13. }
14. }

Interface inheritance
A class implements interface but one interface extends another interface .

1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class TestInterface4 implements Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11. public static void main(String args[]){
12. TestInterface4 obj = new TestInterface4();
13. obj.print();
14. obj.show();
15. }
16. }

Java 8 Default Method in Interface


Since Java 8, we can have method body in interface. But we need to make it default
method. Let's see an example:

File: TestInterfaceDefault.java

1. interface Drawable{
2. void draw();
3. default void msg(){System.out.println("default method");}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8. class TestInterfaceDefault{
9. public static void main(String args[]){
10. Drawable d=new Rectangle();
11. d.draw();
12. d.msg();
13. }}

Java 8 Static Method in Interface


Since Java 8, we can have static method in interface. Let's see an example:

File: TestInterfaceStatic.java

1. interface Drawable{
2. void draw();
3. static int cube(int x){return x*x*x;}
4. }
5. class Rectangle implements Drawable{
6. public void draw(){System.out.println("drawing rectangle");}
7. }
8.
9. class TestInterfaceStatic{
10. public static void main(String args[]){
11. Drawable d=new Rectangle();
12. d.draw();
13. System.out.println(Drawable.cube(3));
14. }}

What is marker or tagged interface?


An interface that have no member is known as marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are used to provide some essential information to
the JVM so that JVM may perform some useful operation.

1. //How Serializable interface is written?


2. public interface Serializable{
3. }
Nested Interface in Java
Note: An interface can have another interface i.e. known as nested interface. We will learn it
in detail in the nested classes chapter. For example:

1. interface printable{
2. void print();
3. interface MessagePrintable{
4. void msg();
5. }
6. }

Abstract class Interface

1) Abstract class can have abstract and non- Interface can have only abstract methods. Since J
abstract methods. can have default and static methods also.

2) Abstract class doesn't support multiple Interface supports multiple inheritance.


inheritance.

3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.

4) Abstract class can provide the Interface can't provide the implementation of a
implementation of interface. class.

5) The abstract keyword is used to declare The interface keyword is used to declare interface
abstract class.

6) Example: Example:
public abstract class Shape{ public interface Dr
public abstract void draw(); void
} }

Example of abstract class and interface in Java


Let's see a simple example where we are using interface and abstract class both.
1. //Creating interface that has 4 methods
2. interface A{
3. void a();//bydefault, public and abstract
4. void b();
5. void c();
6. void d();
7. }
8.
9. //Creating abstract class that provides the implementation of one method of A interface
10. abstract class B implements A{
11. public void c(){System.out.println("I am C");}
12. }
13.
14. //Creating subclass of abstract class, now we need to provide the implementation of rest of
the methods
15. class M extends B{
16. public void a(){System.out.println("I am a");}
17. public void b(){System.out.println("I am b");}
18. public void d(){System.out.println("I am d");}
19. }
20.
21. //Creating a test class that calls the methods of A interface
22. class Test5{
23. public static void main(String args[]){
24. A a=new M();
25. a.a();
26. a.b();
27. a.c();
28. a.d();
29. }}

Вам также может понравиться