-
Notifications
You must be signed in to change notification settings - Fork 0
/
InheritanceExample.java
95 lines (77 loc) · 1.7 KB
/
InheritanceExample.java
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
class Animal
{
private int legs;
private String color;
private boolean vegitarian;
Animal()
{
legs = 0;
color = "";
vegitarian = false;
}
Animal(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 isVegitarian()
{
return vegitarian;
}
public void setVegitarian(boolean vegitarian)
{
this.vegitarian = vegitarian;
}
}
class Cat extends Animal
{
Cat(int legs, String color, boolean vegitarian)
{
super(legs, color, vegitarian);
}
}
class Dog extends Animal
{
Dog(int legs, String color, boolean vegitarian)
{
super(legs, color, vegitarian);
}
}
public class InheritanceExample
{
public static void main(String[] args)
{
var kattie = new Cat(4, "White", false);
System.out.println("Cat has " + kattie.getLegs() + " legs");
System.out.println("Cat color is " + kattie.getColor());
System.out.println("Is cat a vegitarian? " + kattie.isVegitarian());
// Cat c = new Cat(4, "Black", false);
// Dog d = new Dog(4, "White", false);
// Animal a = c;
// boolean flag = c instanceof Cat; // normal case, returns true
// System.out.println(flag);
// flag = c instanceof Animal; // returns true since c is-an Animal too
// System.out.println(flag);
// flag = a instanceof Cat; // returns true because a is of type Cat at runtime
// System.out.println(flag);
// flag = a instanceof Dog; // returns false for obvious reasons.
// System.out.println(flag);
}
}