-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstractionExample.java
More file actions
95 lines (80 loc) · 2.29 KB
/
AbstractionExample.java
File metadata and controls
95 lines (80 loc) · 2.29 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
84
85
86
87
88
89
90
91
92
93
94
package Java_OOP;
// Abstraction in Java
/**
* Abstraction is the process of hiding complex implementation details
* and showing only the essential features to the user.
*
* In Java, abstraction can be achieved in two ways:
*
* 1. Abstract Classes (0–100% abstraction)
* - Declared with the 'abstract' keyword.
* - Can have both abstract methods (no body) and concrete methods.
* - Cannot be instantiated directly.
*
* 2. Interfaces (100% abstraction)
* - Declared with the 'interface' keyword.
* - All methods are abstract by default (until Java 8, which added default/static methods).
* - A class implements an interface to provide its behavior.
*/
public class AbstractionExample {
public static void main(String[] args) {
// --- Abstract Class Example ---
System.out.println("Abstract Class Example:");
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.makeSound();
myDog.eat();
myCat.makeSound();
// --- Interface Example ---
System.out.println("\nInterface Example:");
Vehicle car = new Car();
Vehicle bike = new Motorcycle();
car.start();
bike.start();
car.stop();
bike.stop();
}
}
// Example 1: Abstract Class
abstract class Animal {
// Abstract method (no body) — must be implemented by subclasses
abstract void makeSound();
// Concrete method — can be used by all subclasses
void eat() {
System.out.println("This animal is eating...");
}
}
// Subclasses provide specific implementations
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("The dog barks!");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("The cat meows!");
}
}
// Example 2: Interface
interface Vehicle {
void start();
void stop();
}
class Car implements Vehicle {
public void start() {
System.out.println("Car is starting...");
}
public void stop() {
System.out.println("Car is stopping...");
}
}
class Motorcycle implements Vehicle {
public void start() {
System.out.println("Motorcycle is starting...");
}
public void stop() {
System.out.println("Motorcycle is stopping...");
}
}