In: Computer Science
Explain an Is-a relationship between classes in Java
Is-a relationship between classes:
Inheritance is Java can be done by implementing either Class Inheritance or Interface Inheritance. The notion of Is-a of classes is based on the Inheritance in Java. In Java, we can implement Is-a relationship between classes using the extends keyword or implements keyword in a class declaration.
It signifies that a child class will inherit all attributes and methods of the parent class, and this relationship is unidirectional in nature, for example, A car is a vehicle. But the reverse is not true, ie All vehicles are not a car.
Example:
package transport;
//Declare a parent class Vehicle
class Vehicle{
private double price;
public void setPrice(double price) {
this.price= price;
}
public double getPrice() {
return price;
}
}
//Car has Is-a relationship with Vehicle
//Car inherits price from parent class Vehicle
Class Car extends Vehicle{
private String colour;
public void setColour(String colour) {
this.colour= colour;
}
public void getColour() {
return colour;
}
}