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
- class Subclassname extends Superclassname
- {
- //methods and fields
- }
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.
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:
Single inheritance example:
- 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...
For kaspersky and office installtion guide visit activation.kaspersky.com and office.com/setup
Multilevel inheritance example:
- 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...