-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathInheritanceExample.java
More file actions
80 lines (63 loc) · 2.01 KB
/
InheritanceExample.java
File metadata and controls
80 lines (63 loc) · 2.01 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
package src;
class AnimalClass {
private int legs;
private String color;
private boolean vegitarian;
AnimalClass() {
legs = 0;
color = "";
vegitarian = false;
}
AnimalClass(int legs, String color, boolean vegitarian) {
this.legs = legs;
this.color = color;
this.vegitarian = vegitarian;
}
public int getLegs() {
return legs;
}
public void setLegs(int legs) {
this.legs = legs;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isVegetarian() {
return vegitarian;
}
public void setVegitarian(boolean vegetarian) {
this.vegitarian = vegetarian;
}
}
class Cat extends AnimalClass {
Cat(int legs, String color, boolean vegetarian) {
super(legs, color, vegetarian);
}
}
class Dog extends AnimalClass {
Dog(int legs, String color, boolean vegetarian) {
super(legs, color, vegetarian);
}
}
public class InheritanceExample {
public static void main(String[] args) {
var kattie = new Cat(4, "White", false);
System.out.println("src.Cat has " + kattie.getLegs() + " legs");
System.out.println("src.Cat color is " + kattie.getColor());
System.out.println("Is cat a vegetarian? " + kattie.isVegetarian());
// src.Cat c = new src.Cat(4, "Black", false);
// src.Dog d = new src.Dog(4, "White", false);
// src.Animal a = c;
// boolean flag = c instanceof src.Cat; // normal case, returns true
// System.out.println(flag);
// flag = c instanceof src.Animal; // returns true since c is-an src.Animal too
// System.out.println(flag);
// flag = a instanceof src.Cat; // returns true because a is of type src.Cat at runtime
// System.out.println(flag);
// flag = a instanceof src.Dog; // returns false for obvious reasons.
// System.out.println(flag);
}
}