Inheritance in java
The process by which one class acquires the properties(data members) and functionalities(methods) of another class is called inheritance.
Inheritance allows us to reuse code, it improves re-usability in your java application.
Note: The biggest advantage of Inheritance is that the code that is already present in base class need not be rewritten in the child class.
Single Inheritance
class Animal { public void eat() { System.out.println("I can eat"); } public void sleep() { System.out.println("I can sleep"); } } class Dog extends Animal { public void bark() { System.out.println("I can bark"); } } public class Helloworld { public static void main(String[] args) { Dog dog1 = new Dog(); dog1.eat(); dog1.sleep(); dog1.bark(); } }
We have created a parent class called Animal and then we created a child class Dog.
When we extend the Animal class in Dog class at that time the dog class has the availability to
access all the methods and variables.
Output:
I can eat
I can sleep
I can bark
As in output, you can see the dog object is able to access the eat and sleep methods which are inside the Animal class.
Multi-Level Inheritance
From the same as above example we have created a new class called BabyDog. Added a new method ,
so while accessing the parent methods we do not face any issues because of multilevel inheritance.
class Animal { public void eat() { System.out.println("I can eat"); } public void sleep() { System.out.println("I can sleep"); } } class Dog extends Animal { public void bark() { System.out.println("I can bark"); } } class BabyDog extends Dog { public void introduce() { System.out.println("I am BabyDog"); } } public class Helloworld { public static void main(String[] args) { BabyDog dog1 = new BabyDog(); dog1.eat(); dog1.sleep(); dog1.bark(); dog1.introduce(); } }
Output:
I can eat I can sleep I can bark I am BabyDog
Hierarchical inheritance
class Animal{ public void eat() { System.out.println("i can eat"); } } class Dog extends Animal{ public void bark() { System.out.println("i can bark"); } } class BabyDog extends Animal{ public void introduce() { System.out.println("i am baby dog"); } } public class Hierarchical { public static void main(String[] args) { BabyDog babyDog= new BabyDog(); babyDog.eat(); babyDog.introduce(); } }
As you can see we have one parent class and two child class Dog and Baby Dog. Both have extending
the same parent class Animal. So both the classes can access the functionalities of animal class.
No comments: