Extending an Abstract Class
- Identify the syntax of Java Abstract Classes and contrast it with the syntax of Java Interfaces
- Distinguish between interfaces and implementations
Here is the abstract Roster
class for your reference:
Roster
public abstract class Roster {
protected Student[] students;
protected int numStudents;
public Roster(int size) {
students = new Student[size];
numStudents = 0;
}
public abstract void add(Student s);
public abstract void remove(Student s);
public abstract Student find(String email);
}
Here is how MoocRoster
extends Roster
:
public class MoocRoster extends Roster {
public MoocRoster(int size) {
super(size);
}
@Override
public void add(Student s) {
// Implementation omitted to save space
}
@Override
public void remove(Student s) {
// Implementation omitted to save space
}
@Override
public Student find(String email) {
// Implementation omitted to save space
}
}
Notice:
-
There is no
abstract
keyword in the declaration ofMoocRoster
. -
There is no
abstract
keyword in the method declarations within theMoocRoster
class; instead, there is@Override
annotation. -
MoocRoster
has access tostudents
andnumStudents
inRoster
since those fields were defined asprotected
. -
MoocRoster
's constructor invokes the constructor ofRoster
(usingsuper(size)
), which constructs thestudents
array and initializes thenumStudents
attribute.