Click to See Complete Forum and Search --> : Interface and abstract class


rnsun89
September 12th, 2000, 03:25 PM
Can anyone explain what is the difference between interface and abstract class? Thanks.

poochi
September 12th, 2000, 08:38 PM
Interface :

1. Can not have method body, can only have method declaration( all methods are abstract ).
2. Can not be intantiated.
3. Can only have constant member variables.

Abstract class :

1. Has to have atleast one abstract method ( or , the class can be specified as abstract
without even having a single abstract method ).
2. Can not be instantiated ( same as interface )
3. Members are dont need to be constant variables.

For more information :

Interface : http://java.sun.com/docs/books/jls/html/9.doc.html#238680
Abstract Class : http://java.sun.com/docs/books/jls/html/8.doc.html#34944

Poochi...

Norm
September 13th, 2000, 07:22 PM
Since different points of view often allow for a better understanding...
Both classes and interfaces are ways to give a TYPE to a variable.
When a class implements an interface, that class is "Promising" to define all the methods as defined in the interface. An interface itself only lists the methods that must be defined, it does not contain any executeable code itself. A class can implement many,many interfaces as long as none of the methods interfere with each other. By implementing an interface, a class can be referenced and accessed by a variable defined as the interface name. For example if AIntF and BIntF are interfaces, and AClass implements them then following works without casting:

AIntF aclass = new AClass();
BintF bClass = new AClass();




An abstract class is an incomplete class(or one that can't be instantiated) that must be completed by extending it and defining the methods that are defined as abstract. In a lot of Sun's classes most of the methods are defined and only a few or even none must be defined. A class can only extend one abstract class. I'm not familiar with the reasons that Sun had for making Container abstract in 1.1 and changing it to be not abstract in 1.2.

Phill
September 15th, 2000, 06:56 AM
Hi there
I would like to correct Poochi on point 3 of
the interface section :
The variables actually become constant because
they are in the interface, they can be declared
as normal ie:

public interface AnInterface{
int anInt = 20;
}

poochi
September 15th, 2000, 10:53 AM
Thanks phil , for pointing me out the error. My Statement should have been
"Every field(variable) declaration in the body of an interface is implicitly public, static, and final"