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
- 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.
No comments:
Post a Comment