Repository navigation
Expand file tree
/
Copy pathinterface_exercise_2.java
More file actions
107 lines (102 loc) · 2.74 KB
/
Copy pathinterface_exercise_2.java
File metadata and controls
107 lines (102 loc) · 2.74 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
95
96
97
98
99
100
101
102
103
104
105
106
107
Exercise 1: Shape Interface
Objective: Understand interfaces and method implementation.
• Task: Create an interface Shape with a method getArea(). Implement this interface in
three classes: Rectangle, Circle, and Triangle. Each class should provide its own
implementation of the getArea() method.
interface shape {
double getarea();
}
class rectangle implements shape{
double length;
double width;
rectangle(double length,double width) {
this.length=length;
this.width=width;
}
public double getarea() {
return length*width;
}
}
class circle implements shape{
double r;
circle(double r) {
this.r=r;
}
public double getarea(){
return 3.14*r*r;
}
}
class triangle implements shape {
double l;
double h;
double b;
triangle(double l,double h,double b){
this.l=l;
this.h=h;
this.b=b;
}
public double getarea(){
return l*h*b;
}
}
public class main{
public static void main(String[] args) {
rectangle r = new rectangle(2,2);
circle c = new circle(2);
triangle t = new triangle(2,2,2);
System.out.println("circle = "+ c.getarea());
System.out.println("rectangle = "+ r.getarea());
System.out.println("triangle = "+ t.getarea());
}
}
Exercise 2: Animal Interface
Objective: Explore interface methods and class implementation.
• Task: Define an interface Animal with a method bark(). Create a class Dog that
implements this interface and overrides the bark() method to print "Dog is barking".
interface animal {
void bark();
}
class dog implements animal {
public void bark() {
System.out.println("dog is barking");
}
}
public class main{
public static void main(String[] args){
dog d = new dog();
d.bark();
}
}
Exercise 3: Flyable Interface
Objective: Learn about multiple implementations of an interface.
• Task: Create an interface Flyable with a method fly_obj(). Implement this interface in
three classes: Spacecraft, Airplane, and Helicopter. Each class should provide its own
implementation of the fly_obj() method.
interface flyable {
void fly();
}
class spacecraft implements flyable {
public void fly() {
System.out.println("it flys in the space");
}
}
class airplane implements flyable {
public void fly(){
System.out.println("it flys in the air");
}
}
class helicopter implements flyable {
public void fly() {
System.out.println("it flys in the air");
}
}
public class main {
public static void main(String[] args){
spacecraft s=new spacecraft();
airplane a=new airplane();
helicopter h=new helicopter();
s.fly();
a.fly();
h.fly();
}
}