Explain types of inheritance with suitable example.
The answer to the “Explain types of inheritance with suitable example.” is given below:
Inheritance in java is one of the core concepts of Object-Oriented Programming. Java Inheritance is used when we have is-a relationship between objects. Inheritance in Java is implemented using extends keyword.
Inheritance in Java is the method to create a hierarchy between classes by inheriting from other classes.
Java Inheritance is transitive – so if Sedan extends Car and Car extends Vehicle, then Sedan is also inherited from Vehicle class. The Vehicle becomes the superclass of both Car and Sedan.
Inheritance is widely used in java applications, for example extending the Exception class to create an application-specific Exception class that contains more information like error codes. For example NullPointerException.
Terms used in inheritance
- Class
- Sub Class/Child Class
- Super Class/Parent Class
- Reusability
Java supports three types of inheritance −
- Single Level inheritance – A class inherits properties from a single class. For example, Class B inherits Class A.
- Multilevel inheritance – A class inherits properties from a class that again has inherits properties
- Hierarchical inheritance – Multiple classes inherits properties from a single class. For example, Class B inherits Class A and Class C inherits Class A.
class Bicycle {
public int gear;
public int speed;
public Bicycle(int gear, int speed)
{
this.gear = gear;
this.speed = speed;
}
public void applyBrake(int decrement)
{
speed -= decrement;
}
public void speedUp(int increment)
{
speed += increment;
}
public String toString()
{
return (“No of gears are ” + gear + “\n”
+ “speed of bicycle is ” + speed);
}
}
class MountainBike extends Bicycle {
public int seatHeight;
public MountainBike(int gear, int speed,
int startHeight)
{
super(gear, speed);
seatHeight = startHeight;
}
public void setHeight(int newValue)
{
seatHeight = newValue;
}
@Override public String toString()
{
return (super.toString() + “\nseat height is ”
+ seatHeight);
}
}
public class Test {
public static void main(String args[])
{
MountainBike mb = new MountainBike(3, 100, 25);
System.out.println(mb.toString());
}
}
In the above program, when an object of MountainBike class is created, a copy of all methods and fields of the superclass acquire memory in this object. That is why by using the object of the subclass we can also access the members of a superclass.
Leave a Reply