Skip to content

Commit d0a513f

Browse files
committed
OOP: Abstraction
1 parent bcb8a67 commit d0a513f

1 file changed

Lines changed: 75 additions & 0 deletions

File tree

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/**
2+
* Sample code used to explain Object Oriented Programming.
3+
* 1.0 - The orginal source code.
4+
* 1.1 - All the properties of Animals have been encapsulated.
5+
* 1.2 - Inheritance is applied by introducing a super class Animal.
6+
* 1.3 - The treatment logic has been moved to the Animals.
7+
* 1.4 - Abstraction is applied to the Animal class and the treatment method.
8+
*
9+
* @version 1.4
10+
* @author L.Gobinath
11+
*/
12+
public class DoctorDemo {
13+
public static void main(String[] args) {
14+
Cat cat = new Cat();
15+
Dog dog = new Dog();
16+
VeterinaryDoctor doctor = new VeterinaryDoctor();
17+
cat.setAge(4);
18+
dog.setAge(2);
19+
doctor.giveTreatment(cat);
20+
doctor.giveTreatment(dog);
21+
}
22+
}
23+
24+
class VeterinaryDoctor {
25+
/**
26+
* Give treatment to any Animals.
27+
* @param animal The animal.
28+
*/
29+
public void giveTreatment(Animal animal) {
30+
animal.treatment();
31+
}
32+
}
33+
/**
34+
* Super class Animal.
35+
* Animal is an abstract class.
36+
*/
37+
abstract class Animal {
38+
private int age;
39+
40+
public int getAge() {
41+
return this.age;
42+
}
43+
44+
public void setAge(int age) {
45+
this.age = age;
46+
}
47+
48+
/**
49+
* Abstract method.
50+
* Sub classes must override this method.
51+
*/
52+
public abstract void treatment();
53+
}
54+
55+
class Cat extends Animal {
56+
@Override
57+
public void treatment() {
58+
if (getAge() < 3) {
59+
System.out.println("Treatment C1");
60+
} else {
61+
System.out.println("Treatment C2");
62+
}
63+
}
64+
}
65+
66+
class Dog extends Animal {
67+
@Override
68+
public void treatment() {
69+
if (getAge() < 5) {
70+
System.out.println("Treatment D1");
71+
} else {
72+
System.out.println("Treatment D2");
73+
}
74+
}
75+
}

0 commit comments

Comments
 (0)