Академический Документы
Профессиональный Документы
Культура Документы
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).
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a
parent object. It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes.
When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover,
you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
o Class: A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a derived
class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the features. It is
also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse the
fields and methods of the existing class when you create a new class. You can use the same fields
and methods already defined in the previous class.
o Types of Inheritance
o There are various types of inheritance as demonstrated below.
o
o 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 −
o Example
o public class extends Animal, Mammal{}
o However, a class can implement one or more interfaces, which has helped Java get rid of the
impossibility of multiple inheritance.
o
The extends keyword indicates that you are making a new class that derives from an existing class. The
meaning of "extends" is to increase the functionality.
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class is
called child or subclass.
Java Inheritance Example
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type
of Employee.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee class
i.e. code reusability.
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
Single Inheritance Example
File: TestInheritance.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:
barking...
eating...
File: TestInheritance2.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}
Output:
weeping...
barking...
eating...
Hierarchical Inheritance Example
File: TestInheritance3.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
Output:
meowing...
eating...
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B
classes have the same method and you call it from child class object, there will be ambiguity to call the
method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you inherit 2
classes. So whether you have same method or different, there will be compile time error.
1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. } }
Compile Time Error
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 {
.....
.....
}
Sample Code
Following is an example demonstrating Java inheritance. In this example, you can observe two classes
namely Calculation and My_Calculation.
Using extends keyword, the My_Calculation inherits the methods addition() and Subtraction() of
Calculation class.
Copy and paste the following program in a file with name My_Calculation.java
Example
class Calculation {
int z;
z = x + y;
z = x - y;
}}
z = x * y;
}
public static void main(String args[]) {
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}}
javac My_Calculation.java
java My_Calculation
Output
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.
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.
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.
class Super_class {
// Instantiating subclass
Sub_class sub = new Sub_class();
sub.display();
super.display();
obj.my_method();
}}
Compile and execute the above code using the following syntax.
javac Super_Demo
java Super
Output
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
class Superclass {
int age;
Superclass(int age) {
this.age = age;
System.out.println("The value of the variable named age in super class is: " +age);
}}
Subclass(int age) {
super(age);
s.getAge();
}}
Compile and execute the above code using the following syntax.
javac Subclass
java Subclass
Output
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.
Now, based on the above example, in Object-Oriented terms, the following are true −
Super:
Example of Child class refering Parent class methods using super keyword
class Parent
{
String name;
public void details()
{
name = "Parent";
System.out.println(name);
}
}
public class Child extends Parent {
String name;
public void details()
{
super.details(); //calling Parent class details() method
name = "Child";
System.out.println(name);
}
public static void main(String[] args)
{
Child cobj = new Child();
cobj.details();
}
}
Parent
Child
Example of Child class calling Parent class constructor using super keyword
class Parent
{
String name;
public Parent(String n)
{
name = n;
}
}
public class Child extends Parent {
String name;
Note: When calling the parent class constructor from the child class using super keyword,
super keyword should always be the first line in the method/constructor of the child class.
Super class reference pointing to Sub class object.
In context to above example where Class B extends class A.
A a=new B();
is legal syntax because of IS-A relationship is there between class A and Class B.