my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Abstract Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Abstract Class " Watch "Abstract Class " New topic

Abstract Class

Bhaswati Karmakar
Ranch Hand

Joined: May 10, 2001
Posts: 32
A) abstract class Ghost {
void haunt();
B) abstract class Ghost {
void haunt(){};
What is the difference between A and B ?
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
Hi Bhaswati,
The first choice will give you a compiler error because you are not specifying a method body.
The second example will compile and run without any errors. You are specifying a method body but it just doesn't do anything!
NOTE: In both your examples, the class Ghost doesn't have to be declared as abstract because no methods inside of it are abstract. Of course, to make your first choice compile you would need to make the haunt method abstract.
Blues Welis

Joined: May 23, 2001
Posts: 6
Hi,then when I need to use abstract method? :confused
thanks in advance
Mikael Jonasson
Ranch Hand

Joined: May 16, 2001
Posts: 158
When you have a class (that might include real classes), that needs to be subclassed to work. If we for example take the superclass Aminmal. In our example we have to subclasses, Fish and Bird. If we want to implement the method "Move", we realise that the Animal it self has no destinct way of doing this. However both the Fish and the Bird does, as do all other animals. Thus we implement Move() as an abstract method in Anmial thus making sure that all animials have a way of moving.
In code this means that if you have a reference of type Animal, the right verion of Move() will be called depending on which instance it refers to.
I agree. Here's the link:
subject: Abstract Class
It's not a secret anymore!