Inheritance: the Basics
One-parent rule You can have only one parent class. You can do this
public class Thing extends AMajig implements Foo, Baz, Bar
{
}
Subtypes, Again
T is a subtype of S if
- T and S are classes and T extends S.
- T and S are interfaces and T extends S.
- T is a class, S is an interface, and T implements S
If a class S extends a class T, then we have an "is-a" relationship. A T is an S.
If a class S implementts an interface T, then we have an "acts-as-a" relationship. A Rectangle acts as a Shape.
Composition The most common relationship between classes. It is a "has-a" relationship. It is the workaday relationship between classes. Inheritance should be used sparingly.
A BigFraction
has two BigInteger
s
as state. This is composition.
A Point
has two int
s
as state. This is also composition.
Abstract classes and the abstract
Keyword
Any class can be declared abstract
and thereby by class-strated
in the sense that you can't make instances.
A bodyless method MUST be declared abstract
.
Any class containing an abstract
method must be declared
abstract
.
A non-abstract class is called concrete.
Any concrete class must implement all methods from:
- Any interfaces it implements.
- Any
abstract
methods from classes that are ancestors. - These contracts can be fulflilled via inheritance.
Interfaces: What the devil is a Default Method?
As of Java8, interfaces are allowed to have static methods. This is safe since static methods cannot be inherited. They can also have default methods. These methods can be overriden if desired by classes implementing the interface.
They are not without controversy. You can read an interesting dialogue on the subject in Stack Overflow. This article is cited in the dialogue. Oracle also has an article about them.