Well, we declare a class abstract when we want to give some ready made behavior to a child, the child will have choice to override their own behavior or just simply inherit from father, this is something that we cannot achieve with Interfaces.
Lets say: We have a Father class Animal for all the animals following listed two behaviors of an animal.
- fly
- sound
Each Animal can sound, but only bird animals can fly…
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
abstract class Animal{
//only the birds are able to fly...
public void fly(){
System.out.println("Only the birds can fly...");
}
//every animal sounds diffrent.
abstract public void sound();
}
class Cat extends Animal{
//A cat cannot fly.
public void sound(){
System.out.println("Meaooww...");
}
}
class Duck extends Animal{
//A Duck can fly…so implement their fly behavior.
public void fly(){
System.out.println("See...Ducks can fly");
}
public void sound(){
System.out.println("Quack Quack!!");
}
}
public class Main{
public static void main(String... args){
Cat cat = new Cat();
cat.fly();
cat.sound();
Duck duck = new Duck();
duck.fly();
duck.sound();
}
}
Abstract class is just like a concept where its child classes are the real things. Similarly Animal itself is not something that exist in real, the Animal cat,duck, dog and so on are real objects…
Therefore, Animal class in above example is an abstract because animal is no more than a concept no one can create an object of Animal in reality Cats, Dogs, Ducks, and etc exists…
Original Post