Friday, May 02, 2008

Abstract classes and Interfaces

In response to some of the questions asked in class today, I compiled some properties of interfaces and abstract classes that should help guide your choice when deciding when to use an Abstract class or an Interface as a parent class.

Neither an Interface nor an Abstract class can be instantiated. Both can be used to as a template for concrete (implemented) child classes.

Interfaces
  • example interface definition:
public interface Monkey {
public double getWeight();
public void setWeight(double w);
public void walk();
public void talk();
}
  • fields (i.e., members, variables) are not allowed
  • all methods are implicitly abstract
  • a child class can implement many interfaces in Java
  • child classes must implement all methods
Abstract Classes
  • example abstract class definition:
public abstract class Monkey {
private double weight;
public Monkey(){
}
public double getWeight(){
return weight;
}
public void setWeight(double w){
weight = w;
}
public abstract void walk();
public abstract void talk();
}
  • may have members (e.g., weight)
  • may have implemented methods (e.g., getWeight, setWeight) and abstract methods (e.g., walk, talk)
  • a child class can only extend a single parent class in Java (multiple inheritance is not allowed)
  • child classes must implement all of the parent's abstract methods
Section 4.4 in Data Structures and Problem Solving in Java discusses this more extensively. 

This talks more about when you might use one, the other, or both. Furthermore, I found some questions and answers about the two that interviewers like to use. ;)

No comments: