Chapter 5.7.2 – Interfaces as Types | Introduction to Programming Using Java

Chapter 5.7.2 – Interfaces as Types | Introduction to Programming Using Java

 

5.7.2 Interfaces as Types

interfaces as types

As with abstract classes, even though you can’t construct an object from an interface, you can declare a variable whose type is given by the interface. For example, if Drawable is the interface given above, and if Line and FilledCircle are classes that implement Drawable, as above, then you could say:

 

Chapter 5.7.2 - Interfaces as Types | Introduction to Programming Using Java

 

A variable of type Drawable can refer to any object of any class that implements the Drawable interface. A statement like figure.draw(g), above, is legal because figure is of type Drawable, and any Drawable object has a draw() method. So, whatever object figure refers to, that object must have a draw() method.

Note that a type is something that can be used to declare variables. A type can also be used to specify the type of a parameter in a subroutine, or the return type of a function. In Java, a type can be either a class, an interface, or one of the eight built-in primitive types. These are the only possibilities. Of these, however, only classes can be used to construct new objects.

An interface can also be the base type of an array. For example, we can use an array type Drawable[ ] to declare variables and create arrays. The elements of the array can refer to any objects that implement the Drawable interface:

 

Chapter 5.7.2 - Interfaces as Types | Introduction to Programming Using Java

 

Every element of the array will then have a draw() method, so that we can say things like

 

Chapter 5.7.2 - Interfaces as Types | Introduction to Programming Using Java

 

 

 

Read More…

Introduction to Programming Using Java – David J. Eck

Chapter 5.2 – Constructors and Object Initialization | Introduction to Programming Using Java

Chapter 5.2.2 – Constructors | Introduction to Programming Using Java

Chapter 5.5.3 – Example: Vehicles | Introduction to Programming Using Java

Chapter 5.6 – This and Super | Introduction to Programming Using Java

Chapter 5.7 – Interfaces | Introduction to Programming Using Java

1 thought on “Chapter 5.7.2 – Interfaces as Types | Introduction to Programming Using Java”

Leave a Comment