go to previous page   go to home page   go to next page highlighting

Answer:

Both. Usually objects in the world can be regarded in several ways.


Interface

With object oriented programming, you define software objects that mimic "real world" objects. This makes programs easier to think about and more reliable. In the real world, you often think about an object in several different ways. You can think of your car as a vehicle or as taxable property. It would be convenient if software objects, also, could be thought of in several ways. But a Java object belongs to just one class.

An interface is a description of some of the methods that must be included in a class. The methods may be part of the class definition or or inherited from a parent. Often the methods listed in the interface are in addition to those inherited from a parent. An interface may also list constants that can be used by a class.

An interface lets you describe what several classes have in common even if they are in different class hierarchies. This helps you organize code in a consistent manner.

For example, a class Car might extend the Vehicle class. Inheritance then gives it all the methods and instance variables of Vehicle. If Car also implements the Taxable interface, then it includes the methods listed in Taxable. A TV set might also be Taxable, but would not extend Vehicle.

An interface is a list of method headers and constants. An interface usually does not have bodies for the methods it lists, just the headers. A class that implements an interface must include each of the methods listed in the interface, either by inheritance or by implementation.

In recent versions of Java (version 8 and following) an interface may also contain default implementations of methods. This is a specialized feature only occasionally useful and not covered further in this chapter.

A class can extend just one parent class to inherit the methods and instance variables of that parent. A class can implement an interface by defining or inheriting the methods in the interface. A class can implement more than one interface.

An interface is a list of methods expected to be part of the class. Unless the class is abstract, all the methods in the interface must be part of the class. If a class implements only some of the methods in an interface the class must be declared abstract.


QUESTION 2:

Can an interface include instance variables?


go to previous page   go to home page   go to next page