This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
what is the difference between interface and abstrct classes? If interface can be used instead of abstract classes,why abstract classes are provided in java?
Barry Gaunt
Ranch Hand
Joined: Aug 03, 2002
Posts: 7729
posted
0
An abstract class is like any other class except that at least one of its methods is declared abstract to indicate that it is not implemented in the class. With that in mind, if you compare a normal class with an interface you will see a vast difference between the two. -Barry [ August 31, 2002: Message edited by: Barry Gaunt ]
Welcome to the ranch Rahul. Bruce Eckel recommends using an interface, instead of using an abstract class, whenever some common behaviour in the base class isn't needed. It's possible to simulate multiple inheritance with interfaces, but not with abstract classes. A reason to make abstract a class that hasn't got abstract methods, is to make explicit that it cannot be instantiated.
SCJP2. Please Indent your code using UBB Code
Thomas Paul
mister krabs
Ranch Hand
Joined: May 05, 2000
Posts: 13974
posted
0
Barry is almost correct. Abstract classes do not have to have any abstract methods. The Java API has several abstract classes without abstract methods. You make a class abstract when instantiating it doesn't make any sense but instantiating a child of the class does make sense.
An abstract class without at least one abstract method :roll: ! I thought you were pulling my leg, but you are correct.
does in fact compile.
Barkat Mardhani
Ranch Hand
Joined: Aug 05, 2002
Posts: 787
posted
0
Take it to other extreeme. What if all methods of an abstract class are abstract. Is it now as good as an interface? Not quite so. I can think of following differences: 1. all class level variables in an interface are automatically final and static but in case of abstract class, you will have to explicitly declare them static and final. But that gives you some flexibility i.e. you can have some static, final var and others non-static, non-final at that level of abstractation. 2. any implementing class will be limited to this (abstract) class as a base class. Alternatively, if these abstract methods are implemented in an interface, the implementing class can draw from more than one class and still have opportunity to extend another class. Thanks Barkat
The MouseAdapter is a good example, Thomas, I never noticed that it was abstract; I just remembered that it had methods to be overridden. When meeting java's abstract modifier during an introduction to java, I took note of the fact that if a method is declared as abstract then the class had to be declared abstract. That seemed to be a bit redundant at the time. Now it makes a little more sense. -Barry [ September 01, 2002: Message edited by: Barry Gaunt ]