Inheritance in java with simple examples

Inheritance in Java is a process in which one object acquires all the properties and behaviors of a parent object. It is an important part of 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.

 

     Why we use inheritance in java:

  • It helps in code reusability
  • It is used for method overriding

For office installation and setup visit office.com/setup 

The Basic syntax of Java Inheritance

  1. class Subclassname extends Superclassname  
  2. {  
  3.    //methods and fields  
  4. }  

 

The use of  extends keyword indicates that you are making a new class that is derived  from an existing class. 

 

Types of inheritance in java

There can be three types of inheritance in java:

  • single
  • multilevel
  • hierarchical.

 

Types of inheritance in Java

For norton & mcafee installation guide visit norton.com/setup and mcafee.com/activate

 

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Multiple inheritance in Java

Single inheritance example:

  

  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...

For kaspersky and office installtion guide visit activation.kaspersky.com and office.com/setup

Multilevel inheritance example:
  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...
posted @ 2020-09-07 04:40  OFFICE  阅读(49)  评论(0编辑  收藏  举报