Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 8a2b14e

Browse files
added more programs
1 parent 4d6c5a4 commit 8a2b14e

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

‎11_OOPs/OwnPractise/Main.java

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Interface (Abstraction)
2+
interface Vehicle {
3+
void start();
4+
void stop();
5+
}
6+
7+
// Base Class (Encapsulation with private fields)
8+
class Car implements Vehicle {
9+
private String brand;
10+
private int year;
11+
12+
// Constructor
13+
public Car(String brand, int year) {
14+
this.brand = brand;
15+
this.year = year;
16+
}
17+
18+
// Getters and Setters (Encapsulation)
19+
public String getBrand() {
20+
return brand;
21+
}
22+
23+
public int getYear() {
24+
return year;
25+
}
26+
27+
public void start() {
28+
System.out.println(brand + " is starting...");
29+
}
30+
31+
public void stop() {
32+
System.out.println(brand + " has stopped.");
33+
}
34+
35+
public void displayDetails() {
36+
System.out.println("Brand: " + brand + ", Year: " + year);
37+
}
38+
}
39+
40+
// Derived Class (Inheritance)
41+
class ElectricCar extends Car {
42+
private int batteryLife;
43+
44+
public ElectricCar(String brand, int year, int batteryLife) {
45+
super(brand, year); // calling parent constructor
46+
this.batteryLife = batteryLife;
47+
}
48+
49+
// Overriding Method (Polymorphism)
50+
@Override
51+
public void start() {
52+
System.out.println(getBrand() + " (Electric) is starting silently...");
53+
}
54+
55+
public void displayBattery() {
56+
System.out.println("Battery Life: " + batteryLife + "%");
57+
}
58+
}
59+
60+
// Main Class
61+
public class Main {
62+
public static void main(String[] args) {
63+
Car myCar = new Car("Toyota", 2020);
64+
myCar.start();
65+
myCar.displayDetails();
66+
myCar.stop();
67+
68+
System.out.println();
69+
70+
ElectricCar myEV = new ElectricCar("Tesla", 2023, 85);
71+
myEV.start();
72+
myEV.displayDetails();
73+
myEV.displayBattery();
74+
myEV.stop();
75+
}
76+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /