-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstract_Vs_Interface.java
More file actions
83 lines (65 loc) · 2.52 KB
/
Abstract_Vs_Interface.java
File metadata and controls
83 lines (65 loc) · 2.52 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
/*
This code demonstrates the differences between abstract classes and interfaces in Java.
Feature Comparison:
1. Method Types:
- Abstract classes can have both abstract and non-abstract methods.
- Interfaces can only have abstract methods by default but, since Java 8, they can have default and static methods.
2. Multiple Inheritance:
- Abstract classes don't support multiple inheritance.
- Interfaces do support multiple inheritance.
3. Variable Types:
- Abstract classes can have final, non-final, static, and non-static variables.
- Interfaces only allow static and final variables.
4. Implementation:
- Abstract classes can implement interfaces.
- Interfaces cannot provide the implementation of an abstract class.
5. Keyword Usage:
- Abstract classes use the "abstract" keyword.
- Interfaces use the "interface" keyword.
6. Access Modifiers:
- Abstract class members can have various access modifiers.
- Interface members are `public` by default.
*/
// Interface example: Defines four abstract methods (implicitly public and abstract)
interface Action {
void actionA();
void actionB();
void actionC();
void actionD();
}
// Abstract class example: provides partial implementation of the Action
// interface
abstract class PartialAction implements Action {
// Implementing one of the methods
public void actionC() {
System.out.println("I am actionC in the abstract class PartialAction");
}
// Other methods remain abstract and must be implemented by any concrete
// subclass
}
// Concrete class implementing all remaining methods of the Action interface
class ConcreteAction extends PartialAction {
// Providing implementation for the remaining abstract methods
public void actionA() {
System.out.println("I am actionA");
}
public void actionB() {
System.out.println("I am actionB");
}
public void actionD() {
System.out.println("I am actionD");
}
}
// Main class to test the interface and abstract class
public class Abstract_Vs_Interface {
public static void main(String[] args) {
// Using polymorphism to refer to the ConcreteAction object with an Action
// interface reference
Action action = new ConcreteAction();
// Calling the methods to show interface and abstract class functionality
action.actionA();
action.actionB();
action.actionC();
action.actionD();
}
}