Description
Objectives
-
Apply the concept of inheritance to design an application.
-
Design a class that makes use of an interface.
1 – Inheritance and polymorphism
-
A class (child) is said to be derived from another if it inherits from that class (parent).
-
The key word extends is used to signifiy that a class inherits from the given class.
-
When a class is derived from another, this class can access all the methods or instance variables that are declared public or protected.
-
Inheritance makes use of polymorphism. It is possible to call a method of a parent class using the key word super.
The word polymorphism derives from the words poly meaning “many”, and morphism meaning “behaviour”. In Java, polymorphism means that an instance of a class (an object) can be used as if it were of different types, thus having many behaviours. Here, a type means a class is derived from another class or an interface.
2 – Interfaces
You can use interfaces in Java as a way to achieve polymorphism.
public
interface
GreetingsInterface
{
// An interface cannot contain an implementation
// of the method, only the signature
public
abstract
void
sayGreetings
();
}
Although the language allows you to declare constants in an interface, the general best practice is to avoid placing constants in interfaces and to only declare abstract methods.
The methods however need to be implemented by some class before you can execute them. All the methods in an interface are public and abstract, even if you leave out the “public” and “abstract” keywords.
To use an interface you must implement that interface in some Java class.
// The key word implements signals to the compiler
// that the SpanishGreetings class implements the
// GreetingsInterface interface
public
class
SpanishGreetings
implements
GreetingsInterface
{
// A class that implements an interface must implement
// all the methods declared in the interface
public
void
sayGreetings
()
{
System
.
out
.
println
(
"Hola"
);
}
}
public
class
JapaneseGreetings
implements
GreetingsInterface
{
public
void
sayGreetings
()
{
System
.
out
.
println
(“
Konnichiwa
”);
}
}
Once a class implements an interface you safe the reference of an instance of that class in a reference variable whose type is the name of the interface. Here is an example of a main method:
public
static
void
main
(
String
[]
args
){
// The variable is declared of interface type GreetingsInterface,
// the object created is of type SpanishGreetings
GreetingsInterface myGreetings
=
new
SpanishGreetings
();
myGreetings
.
sayGreetings
();
// The variable is declared of interface type GreetingsInterface,
// the object created is of type JapaneseGreetings
myGreetings
=
new
JapaneseGreetings
();
myGreetings
.
sayGreetings
();
}