Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Abstract Class

 
Bhaswati Karmakar
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A) abstract class Ghost {
void haunt();
}
B) abstract class Ghost {
void haunt(){};
}
What is the difference between A and B ?
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Regards,
Manfred.
 
Blues Welis
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,then when I need to use abstract method? :confused
thanks in advance
 
Mikael Jonasson
Ranch Hand
Posts: 158
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
ok?
/Mike
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic