Sie sind auf Seite 1von 2

Inheritance in java:

Inheritance is the process that enables one class to acquire the properties
(methods and variable) of another.

With inheritance, the information is placed in a more manageable, hierarchical


order.

The class inheriting the properties of another is the subclass(also called


the derived class, or child class.)

The class whose properties are inherited is the superclass(base class,


parent class).

To inherit from a class, use "extend" keyword. This example shows how to have
the Dog class to inherit from the class animal.

class Dog extends Animal{


//code block
}

Here, Dog is the subclass(child class), and Animal is the superclass


(parent class).

Uses of Inheritance:
->For Method Overriding(so runtime polymorphism can be achieved).
->For Code Reusability.

Terms used in inheritance:

Class: A group of objects which have common properties.


It is a template or blue-print from which objects are created.

Sub Class/Child class: Sub class is a class which inherits the other class.
It is also called derived class, extended class or child class.

Superclass/Parent class:Superclass is the class from where a subclass


the inherited features.
It is also called the base class or a parent class.

Reusability: As the name specifies, Reusability is a mechanism which facilitates


you to reuse the fields and methods of the exiting class when you create a new
class.
You can use the same fields and methods already defined in the previous class.

Single inheritance Example:

class Animal{
void eat(){
System.out.println("eating...");
}
}
class Dog extend Animal{
void bark(){
System.out.println("barking...");
}
}
class Test_inheritance{
public static void main(String [] args){
Dog d =new Dog();
d.bark(); d.eat();
}
}

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 class inherits A and
B classes. If A and B class 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 class . So whether you have same method or different
there will be compile time errors

class A{
void msg(){
System.out.println("hello");
}
}
class B{
void msg(){
System.out.println("welcome");
}
}
class C extends A, B{
*/NOTE: in reality A,B inheritance not possible or multiple inheritance*/
/*just assume if it is possible there will be ambiguity as shown below obj.msg()
Public static void main(String[] args){
C obj = new C();
obj.msg();
//Now which msg () method would be invoked ? there will be ambiguity
}
}
so multiple inheritnce is not possible

Das könnte Ihnen auch gefallen