Learning Java: Day 8

Interfaces and Polymorphism
Chapter 8 of Head First Java makes my head spin.  Here they explain how to use the Java keyword interface (this is not a GUI interface nor the generic word 'interface') so subclasses can inherit from multiple 'trees'. Therefore, a class from one inheritance tree can extend a class, and implement an interface, while another class might implement the same interface, but come from a completely different inheritance tree.

Did that make YOUR head spin, too?

When using interface you make all the methods abstract so that any class that is in a IS-A relationship MUST implement (i.e. override) the methods in the interface.  You use an interface when you want to define a role that other classes can play, regardless of where those classes are in the inheritance tree. Got that?

  • When you don't want anyone to make a new object of the class, mark the class with the abstract keyword
  • An abstract class can have both abstract and non-abstract methods.
  • If a class has even one abstract method, the class must be marked abstract.
  • An abstract method has no body, and the declaration ends with a semicolon (no curly braces).
  • A Java interface is like a 100% pure abstract class. It defines only abstract methods

Example from the book:
Pet
abstract void beFriendly();
abstract void play();

To DEFINE an interface:
     public interface Pet {...}    //use 'interface' instead of 'class'

To IMPLEMENT an interface:
     public class Dog extends Canine implements Pet {...}

A class can implement multiple interfaces
     public class Dog extends Animal implements Pet, Saveable, Paintable {...}

Remember: A Java class can have only one parent (superclass), and that parent class defines who you are. But you can implement multiple interfaces, and those interfaces define roles you can play.

We are still learning concepts in this chapter so there is no programming yet, just exercises and puzzles.

Hoo boy...

0 comments:

Post a Comment