Howdy
Yep, a class can extend one class, and -- at the same time -- implement one or more interfaces. For example, class Dog can extend Animal, but implement Pet, and Serializable:
class Animal {
// animal methods
}
interface Pet {
void beFriendly();
}
class Dog extends Animal implements Pet, Serializable {
void beFriendly() {
// tail-wagging code goes here
}
}
What this really says is:
A Dog is a type of Animal.
Inheritance defines what a Dog really IS.
Because of inheritance ('extends'), the Dog inherits things from class Animal.
But... a Dog is capable of playing other roles (wearing other hats).
So a Dog can also play the role of a PET, and do PET behaviors.
A Dog can also play the role of "something that can be Serialized" (which means saved/flattened/persisted)
But some *other* animal might not be appropriate as a Pet. For example, you might say:
class Hippo extends Animal implements Serializable {
}
This says that Hippo is a type of Animal, and is also "something that can be Serialized", but Hippo is not a Pet, and thus has no Pet behaviors.
The cool thing about interfaces is that they can cover things in different inheritance trees. So you can have other things in
Java that are Serializable, for example:
class Book implements Serializable { }
This means class Book doesn't extend anything (except, implicitly, class Object), but it can also be serialized.
Or, you could do...
class RobotDog extends Robot implements Pet {
void beFriendly() { }
}
Now you have a class that is part of a different, non-Animal inheritance tree, but yet still gets to be a Pet. This is one of the coolest things in Java, because now you can treat Animals and certain non-Animals as Pets, polymorphically. (Out of scope to explain
polymorphism here
cheers,
Kathy Sierra
are you wickedly smart? "If you're a developer and you want to learn Java, dive in... Head First." --Scott McNealy