-
Notifications
You must be signed in to change notification settings - Fork 1
/
Vehicle02.java
54 lines (44 loc) · 1.41 KB
/
Vehicle02.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Parent class
class Vehicle {
protected String brand;
public Vehicle(String brand) {
this.brand = brand;
}
public void honk() {
System.out.println("Beep beep!");
}
}
// Child class inheriting from Vehicle
class Car extends Vehicle {
private int numDoors;
public Car(String brand, int numDoors) {
super(brand);
this.numDoors = numDoors;
}
public void drive() {
System.out.println("Driving the car with " + numDoors + " doors.");
}
}
// Child class inheriting from Vehicle
class Motorcycle extends Vehicle {
private boolean hasSidecar;
public Motorcycle(String brand, boolean hasSidecar) {
super(brand);
this.hasSidecar = hasSidecar;
}
public void ride() {
if (hasSidecar) {
System.out.println("Riding the motorcycle with a sidecar.");
} else {
System.out.println("Riding the motorcycle without a sidecar.");
}
}
public static void main(String[] args) {
Car car = new Car("Toyota", 4);
car.honk(); // Inherited method from Vehicle class
car.drive(); // Method specific to Car class
Motorcycle motorcycle = new Motorcycle("Honda", false);
motorcycle.honk(); // Inherited method from Vehicle class
motorcycle.ride(); // Method specific to Motorcycle class
}
}