-
Notifications
You must be signed in to change notification settings - Fork 0
/
Inheritance.java
71 lines (56 loc) · 1.34 KB
/
Inheritance.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
public class Animal
{
public String name;
public int age;
public Animal()
{
}
public Animal(String name)
{
this.name = name;
}
}
public class Dog extends Animal
{
public boolean licensed;
public Dog(String name)
{
super(name); // Invoke superclass constructor.
}
public void bark()
{
System.out.println(super.name + " says BARK!");
}
}
public class Cat extends Animal
{
public boolean isPersian;
public Cat(String name, int age)
{
super(name);
super.age = age; // Access superclass field.
}
public void meow()
{
System.out.println(super.name + " says MEOW!");
}
}
public class Animals
{
public static void main(String []args)
{
Dog myDog = new Dog();
myDog.name = "rover";
myDog.age = 3;
Cat myCat = new Cat("kitty", 3);
myCat.age = 1; // Change the age field from 3 to 1.
myDog.licensed = true;
myCat.isPersian = true;
myDog.bark();
myCat.meow();
System.out.println("My dog " + myDog.name + " is " + myDog.age + " years old");
Animal myAnimal = new Animal("roger");
myAnimal.age = 5;
myAnimal.bark(); // Fails since bark is not part of Animal.
}
}