-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInheritanceExample.java
More file actions
83 lines (71 loc) · 2.36 KB
/
InheritanceExample.java
File metadata and controls
83 lines (71 loc) · 2.36 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
package Java_OOP;
// Inheritance in Java
/**
* Inheritance allows one class (child/subclass) to inherit
* the fields and methods of another class (parent/superclass).
*
* It promotes code reusability and establishes an "is-a" relationship.
*
* Syntax:
* class SubclassName extends SuperclassName { ... }
*
* Types of Inheritance in Java:
* - Single Inheritance (one class inherits from another)
* - Multilevel Inheritance (a class inherits from another derived class)
* - Hierarchical Inheritance (multiple classes inherit from one parent)
*
* Note:
* - Java does NOT support multiple inheritance with classes
* (to avoid ambiguity), but it can be achieved using interfaces.
*/
// Example 1: Single Inheritance
class Vehicle {
String brand = "Toyota";
void start() {
System.out.println("Vehicle is starting...");
}
}
class Car extends Vehicle {
int wheels = 4;
void drive() {
System.out.println("Car is driving...");
}
}
// Example 2: Multilevel Inheritance
class ElectricCar extends Car {
int batteryCapacity = 85;
void charge() {
System.out.println("Electric car is charging...");
}
}
// Example 3: Hierarchical Inheritance
class Motorcycle extends Vehicle {
void ride() {
System.out.println("Motorcycle is riding...");
}
}
public class InheritanceExample {
public static void main(String[] args) {
// --- Single Inheritance ---
System.out.println("Single Inheritance Example:");
Car myCar = new Car();
System.out.println("Brand: " + myCar.brand);
System.out.println("Wheels: " + myCar.wheels);
myCar.start(); // inherited from Vehicle
myCar.drive();
// --- Multilevel Inheritance ---
System.out.println("\nMultilevel Inheritance Example:");
ElectricCar myTesla = new ElectricCar();
System.out.println("Brand: " + myTesla.brand);
System.out.println("Battery Capacity: " + myTesla.batteryCapacity + " kWh");
myTesla.start(); // from Vehicle
myTesla.drive(); // from Car
myTesla.charge(); // from ElectricCar
// --- Hierarchical Inheritance ---
System.out.println("\nHierarchical Inheritance Example:");
Motorcycle myBike = new Motorcycle();
System.out.println("Brand: " + myBike.brand);
myBike.start();
myBike.ride();
}
}