Java Reference
In-Depth Information
abstract class A {
abstract void doSomething ();
}
abstract class B extends A {
// Does not provide a concrete implementation
// of doSomething ()
void doSomethingElse () { ... }
}
This code compiles without errors. Of course, classes A and B may never be
instantiated directly (since they are abstract). Eventually, there must be some
subclass of A or B that provides a concrete implementation of all the abstract
methods:
class C extends B {
// Provides a concrete implementation of doSomething()
void doSomething () {...}
}
4.5 Interfaces
As discussed in Section 4.2, Java does not allow a class to inherit directly from
more than one class. That is,
class Test extends AClass, BClass // Error!!
There are situations where multiple inheritance could be useful, but it can also
lead to problems; an example is dealing with the ambiguity when the inherited
classes include methods and fields with the same identifiers (i.e. the names and
parameter lists).
Interfaces provide most of the advantages of multiple inheritance with fewer
problems. An interface is basically an abstract class but with all methods abstract.
The methods in an interface do not need an explicit abstract modifier since
they are abstract by definition. A concrete class implements an interface rather
than extends it, and a class can implement more than one interface. Any class
that implements an interface must provide an implementation of each interface
method (or be declared abstract).
In the example below, Runnable is an interface with a single method:
run() .Any class that implements Runnable must provide an implementation of
run() .
Search WWH ::




Custom Search