What is Inheritance? what are its types? In general inheritance means take some qualities or behaves from our parents or grandparents. Do you thing inheritance it is related to java? well, YES! it is related to java but why and how? To know that read the following carefully and completely.
INHERITANCE.
It is always a good idea to reuse something rater then creating or writing them from the beginning again.
Inheritance in java, is the process of deriving a new class from an existing class.
The existing class is known base, parent or super class.
The derived class is known as derived,child or subclass.
Defining a subclass.
class derivedclassname extend superclassname
{
//data member.
//member function.
}
example:
class box
{
int length:
int breath:
int height:
}
class colourbox extends box
{
string color;
string weight;
}
Types of inheritances.
- Single inheritances.
- multilevel inheritances.
- Hierarchical inheritances.
- multiple inheritances.
- Hybrid inheritances.
Single inheritances.
If a new class is derived from existing class then it is called single inheritances.
syntax:
class baseclass
{
//data member.
//member function.
}
class derivedclass extend baseclass
{
//data member.
//member function.
}
Multilevel inheritances.
If a class is derived from a class, even that class is also derived from another class then it is said to be multilevel inheritances
syntax:
class baseclass
{
//data member.
//member function.
}
class derivedclass-1 extend baseclass
{
//data member.
//member function.
}
class derivedclass-2 extend derivedclass-1
{
//data member.
//member function.
}
Hierarchical inheritances.
If to or more class are derives from baseclass it is called hierarchical inheritances.
syntax:
class baseclass
{
//data member.
//member function.
}
class derivedclass-1 extend baseclass
{
//data member.
//member function.
}
class derivedclass-2 extend baseclass
{
//data member.
//member function.
}
Multiple inheritances.
If a class is derived fro one or more base class it is called multiple inheritances.
Java does not support multiple inheritance directly, but class can implement one or more interface, thus makes the completes the task.
Hybrid inheritances.
It is the combination of multiple and multilevel inheritances.
Again java does not support this directly, but class can implement one or more interface, thus makes the completes the task.
Bonus:
SUBCLASS CONSTRUCTOR. (super keyword)
A Subclass constructor is used to construct the instance variable of both the subclass and the super class.
The subclass constructor uses the keyword super to invoke the constructor method of the super class.
Comments
Post a Comment