Top
Previous Next
Java's Object Orientation, I/O CS 161 - Java

Inheritance

You say one class extends another when you want to re-use most of the capabilities of a class, but want to add some additional capabilities, over-ride some, or provide other specialization.
Source: examples/AnyStudent.java



/** encapsulate the characteristics of any one student
** @author: Jonathan Doughty
**/
 
public abstract class AnyStudent {
 
private static long nextId = 0;
 
// Instance variables (fields) that will be associated with each student
 
private String name;
private long id;
private long tuitionPaid;
private long tuitionOwed;
 
// A constructor that will create student objects with specified name and id
public AnyStudent( String studentName) {
name = studentName;
id = nextId;
nextId++;
}
 
// I'm not going to allow other users of the AnyStudent class create
// Students without a name and an id value.
private AnyStudent() {
}
 
public String toString() {
return name + ":" + id;
}
 
public void payTuition(int amount) {
tuitionPaid += amount;
tuitionOwed -= amount;
}
 
public long tuitionOwed() {
return tuitionOwed;
}
}

Source: examples/UnderGradStudent.java



/** encapsulate the characteristics of an UnderGrad student
** @author: Jonathan Doughty
**/
 
public class UnderGradStudent extends AnyStudent {
 
private float GPA;
 
// A constructor that will create student objects with specified name and id
public UnderGradStudent( String studentName) {
super(studentName); // invoke AnyStudent constructor
}
 
public float getGPA() {
return GPA;
}
 
public String toString() {
String basic = super.toString();
return basic + " GPA:" + GPA;
}
 
// Other methods associated with being an undergraduate student ...
}

Source: examples/GradStudent.java



/** encapsulate the characteristics of a Grad student
** @author: Jonathan Doughty
**/
 
public class GradStudent extends AnyStudent {
 
private Faculty advisor;
private Course teachingAssistantFor;
 
// A constructor that will create student objects with specified name and id
public GradStudent( String studentName) {
super(studentName);
}
 
public void writeThesis() {
// mumble
}
 
public String toString() {
String basic = super.toString();
return basic + " grad";
}
 
// Other methods associated with being a grad student ...
}


Top
Previous Next
jwd