-
Notifications
You must be signed in to change notification settings - Fork 1
/
VirtualExample.java
66 lines (57 loc) · 1.48 KB
/
VirtualExample.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
import java.util.LinkedList;
// Animal parent class
class Animal
{
// normal method acting like virtual methods.
public void eat()
{
System.out.println("I eat like a generic Animal.");
}
}
// Fish inherited from Animal class.
class Fish extends Animal
{
// Overriding the Animal class 'eat' method
@Override
public void eat()
{
System.out.println("I eat like a fish.");
}
}
// Goldfish inherited from Animal class.
class GoldFish extends Animal
{
// Overriding the Animal class 'eat' method
@Override
public void eat()
{
System.out.println("I eat like a gold fish.");
}
}
// otherAnimals inherited from Animal class.
class otherAnimals extends Animal
{
// no overriding of 'eat' virtual method.
// therefore, the parent class method will be
// printed on console.
}
// main example class.
public class VirtualExample
{
// main drivan method.
public static void main(String[] args)
{
// Creating a linked list of type 'Animal' class.
LinkedList<Animal> animals = new LinkedList<>();
// Adding the Fish, GoldFish, Animal and otherAnimals class objects.
animals.add(new Fish());
animals.add(new GoldFish());
animals.add(new Animal());
animals.add(new otherAnimals());
// Using the enhanced or for-each loop to iterate over the linkedlist.
for (Animal animal : animals)
{
animal.eat();
}
}
}