How to inherit a variable in Java?
How to inherit a variable in Java?
I'd be happy to help!
Java inheritance example w3schools
I'm happy to help you with the Java inheritance example from W3Schools!
Here's an example of how you can use Java inheritance:
// Parent class (Vehicle)
class Vehicle {
private String color;
public Vehicle(String color) {
this.color = color;
}
public void display() {
System.out.println("I am a " + color + " vehicle.");
}
}
// Child class (Car) inherits from the Vehicle class
class Car extends Vehicle {
private int speed;
public Car(String color, int speed) {
super(color); // Calls the parent constructor
this.speed = speed;
}
@Override
public void display() {
System.out.println("I am a " + getColor() + " car that goes at a speed of " + speed + ".");
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("red", 120);
myCar.display(); // Output: I am a red car that goes at a speed of 120.
Vehicle v = myCar;
v.display(); // Output: I am a red vehicle.
}
}
In this example, Vehicle
is the parent class and Car
is the child class. The Car
class inherits properties from the Vehicle
class. You can see that the Car
constructor calls the Vehicle
constructor using super(color)
.
The display()
method in the Car
class overrides the one in the Vehicle
class, providing a specific implementation for cars. In this example, when you create an instance of Car
and call its display()
method, it prints out a message with the car's color and speed.
In the Main
class, we demonstrate inheritance by creating an instance of Car
, calling its display()
method, and then casting that instance to Vehicle
. When we call the display()
method on the Vehicle
reference, we see that it inherits the behavior from the parent class.
I hope this helps!