Give three solid situations for when to use inheritance in java. Explain all situations with examples.
Give three solid situations for when to use inheritance in java. Explain all situations with examples.
1. IS-A situation:
Vehicle is a class, which has some properties, like: weight,colour,brand,speed,no_of_wheels
now, car is a vehicle. In this case we have to use single inheritance .
import java.io.*;
import java.lang.*;
import java.util.*;
class Vehicle {
String brand;
String color;
double weight;
double speed;
public void move()
{
System.out.println("is moving");
}
}
class Car extends Vehicle {
String licenseNumber;
String owner;
String bodyStyle;
public void type() { System.out.println("car"); }
public static void main(String args[]) {
System.out.println(new Vehicle().brand);
System.out.println(new Car().brand);
System.out.println(" ");
new Car().type();
new Car().move();
}
}
Output:
As there is no brand name is mentioned so it is null.
Step by step
Solved in 3 steps with 6 images