Provide Best Programming Tutorials

Interfaces vs. Abstract Classes

A class can implement multiple interfaces, but it can only extend one superclass.

An interface can be used more or less the same way as an abstract class, but defining an interface is different from defining an abstract class. The table below summarizes the differences.

 

 

 

 

Java allows only single inheritance  for class extension, but allows multiple extensions  for interfaces. For example,

public class NewClass extends BaseClass
implements Interface1, ... , InterfaceN {
   ...
}

An interface can inherit other interfaces using the extends keyword. Such an interface is called a subinterface . For example, NewInterface in the following code is a subinterface of Interface1 , . . . , and InterfaceN .

public interface NewInterface extends Interface1, ... , InterfaceN {
// constants and abstract methods
}

A class implementing NewInterface must implement the abstract methods defined in NewInterface , Interface1 , . . . , and InterfaceN . An interface can extend other interfaces, but not classes. A class can extend its superclass and implement multiple interfaces.

A class implementing NewInterface must implement the abstract methods defined in NewInterface , Interface1 , . . . , and InterfaceN . An interface can extend other interfaces, but not classes. A class can extend its superclass and implement multiple interfaces.

All classes share a single root, the Object class, but there is no single root for interfaces. Like a class, an interface also defines a type. A variable of an interface type can reference any instance of the class that implements the interface. If a class implements an interface, the interface is like a superclass for the class. You can use an interface as a data type and cast a variable of an interface type to its subclass, and vice versa. For example, suppose c is an instance of Class2 in Figure 13.7. c is also an instance of Object , Class1 , Interface1 , Interface1_1 , Interface1_2 , Interface2_1 , and Interface2_2 .

In general, interfaces are preferred over abstract classes because an interface can define a common supertype for unrelated classes. Interfaces are more flexible than classes.

 

Leave a Reply

Close Menu