Java Week - 8
Java Week - 8
Inheritance in java
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).
When a child class(newly defined abstraction) inherits(extends) its parent class (being
inherited abstraction), all the properties and methods of parent class becomes the
member of child class.
In addition, child class can add new data fields(properties) and behaviors(methods),
and
It can override methods that are inherited from its parent class.
Inheritance Basics
The keyword extends is used to define inheritance in Java.
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.
Syntax:-
class subclass-name extends superclass-name {
// body of the class
}
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.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Programmer salary is:40000.0
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Output:
barking...
eating...
2) Multilevel Inheritance:
In Multilevel Inheritance, a derived class will be inheriting a base class and as well as
the derived class also act as the base class to other class i.e. a derived class in turn acts
as a base class for another class.
Multilevel Inheritance Example:-
As you can see in the example given below, BabyDog class inherits the Dog
class which again inherits the Animal class, so there is a multilevel inheritance.
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Output:
weeping...
barking...
eating...
3) Hierarchical Inheritance:
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than
one sub class
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}
}
Output:
meowing...
eating...
4) Hybrid Inheritance
In general, the meaning of hybrid (mixture) is made of more than one thing. In Java, the
hybrid inheritance is the composition of two or more types of inheritance. The main purpose
of using hybrid inheritance is to modularize the code into well-defined classes. It also
provides the code reusability. The hybrid inheritance can be achieved by using the following
combinations:
o Single and Multiple Inheritance (not supported but can be achieved through interface)
o Multilevel and Hierarchical Inheritance
o Hierarchical and Single Inheritance
o Multiple and Multilevel Inheritance
Here class A and class B extends the class C that represents the hierarchical inheritance. On
the other hand, class D extends the class A that represents the single inheritance.
class C
{
public void disp()
{
System.out.println("C");
}
}
class A extends C
{
public void disp()
{
System.out.println("A");
}
}
class B extends C
{
public void disp()
{
System.out.println("B");
}
}
public class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[])
{
D obj = new D();
obj.disp();
}
}
Output:
5) Multiple inheritance
When one class extends more than one classes then this is called multiple inheritance. For
example: Class C extends class A and B then this type of inheritance is known as multiple
inheritance. Java doesn’t allow multiple inheritance.
Why multiple inheritance is not supported in java?
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
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
public static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Output :
Compile Time Error
Output
Baking cake with base as vanilla
Size is 7 inches and weight is 3.0 kg.
Adding white cream
Decorating cake
Adding pineapple pieces
Pineapple cake - 7 inches is ready
Baking cake with base as vanilla
Size is 5 inches and weight is 2.0 kg.
Adding chocolate cream
Decorating cake
Adding chocolate chips
Chocolate cake - 5 inches is ready
Output explanation: ‘Cake’ class is the base class. The base for every cake has a
vanilla flavor. We have two specializations i.e Pineapple and Chocolate flavor cake.
These classes use the Cake’s bake() method to make a vanilla base cake and then add
cream and decorate the cake based on the flavor.
Note: After few days, Jane’s bakery shop sales are high. So she decides to bake cakes
with different bases to offer more varieties to her customers. With these new
requirements, we need to change the ‘Cake’ class constructor, so do the changes in the
above code will be reflected. The code changes are as below. However, we need to
modify the subclasses to accept a 3rd parameter – flavor for the code to work.
Easier to Maintain
The Principle suggests using interfaces. Interfaces in code offers an additional level of
abstraction which in turn enables loose coupling. The implementations of an interface are
independent of each other and don’t need to share any code. Hence, you can easily
maintain your code with client’s keep changing requirements.
Flexibility
When you follow the open closed principle in writing your code, you will have better
flexibility to extend it. Further, if any change request arises in future, your code will be
more flexible to extend.