Inheritance is a mechanism in which one object acquires all the properties and behaviour of another object. The idea behind inheritance is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you reuse (or inherit) methods and fields, and you add new methods and fields to adapt your new class to new situations.Inheritance represents the IS-A relationship.
Why use Inheritance?
- for method overriding
- for code reusability
Syntax of Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
The keyword extends indicates that you are making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is called a superclass. The new class is called a subclass.
types of inheritance:
example of single level inheritance :
class Animal{
void eat(){System.out.println("eating food");}
}
class Dog extends Animal{
void bark(){System.out.println("barking");}
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
Que) Why multiple inheritance is not supported in java? To reduce the complexity and simplify the language,multiple inheritance is not supported in java. | |
No comments:
Post a Comment