-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractClassDemo.java
More file actions
83 lines (63 loc) · 1.76 KB
/
AbstractClassDemo.java
File metadata and controls
83 lines (63 loc) · 1.76 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Abstract class
abstract class Vehicle {
// Variable in abstract class
String brand;
// Constructor in abstract class
Vehicle(String brand) {
this.brand = brand;
System.out.println("Vehicle constructor called for: " + brand);
}
// Abstract method (must be implemented by subclass)
abstract void startEngine();
// Concrete method (normal method)
void stopEngine() {
System.out.println(brand + " engine stopped.");
}
// Final method (cannot be overridden)
final void fuelType() {
System.out.println("This vehicle uses fuel.");
}
// Static method
static void vehicleInfo() {
System.out.println("Vehicles are used for transportation.");
}
}
// First subclass
class Car extends Vehicle {
Car(String brand) {
super(brand); // calling abstract class constructor
}
// Implementing abstract method
@Override
void startEngine() {
System.out.println(brand + " car engine started with key ignition.");
}
}
// Second subclass
class Bike extends Vehicle {
Bike(String brand) {
super(brand);
}
// Implementing abstract method
@Override
void startEngine() {
System.out.println(brand + " bike engine started with self start.");
}
}
// Main class
public class AbstractClassDemo {
public static void main(String[] args) {
// Calling static method
Vehicle.vehicleInfo();
// Abstract class reference (runtime polymorphism)
Vehicle v1 = new Car("Toyota");
v1.startEngine();
v1.stopEngine();
v1.fuelType();
System.out.println();
Vehicle v2 = new Bike("Yamaha");
v2.startEngine();
v2.stopEngine();
v2.fuelType();
}
}