Previous Lecture Lecture 7 Next Lecture

Lecture 7, Mon 04/22

Abstract Methods and Classes

Abstract Methods

Example

// Person.java
public class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String toString() {
    	return "Name: " + name + ", age: " + age;
    }

    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getPerm() { return age; }
    public void setPerm(int age) { this.age = age; }
}
// Student.java
public class Student extends Person {

    private int perm;

    public Student(String name, int age, int perm) {
        super(name, age); // calls Person(name, age);
        this.perm = perm;
    }

    public int getPerm() { return perm; }	
    public void setPerm(int perm) { this.perm = perm; }

    public String toString() {
        System.out.println("In Student.toString()");
        return super.toString() + ", perm: " + perm;
    }
}
public abstract class Student extends Person {
// ...
public abstract double calculateQuarterlyFees();

Subclasses that extend an abstract class have two choices:

Example

// NonResidentStudent.java
public class NonResidentStudent extends Student {

    private String homeState;

    public NonResidentStudent(String name, int age, int perm,
    String homeState) {
        super(name, age, perm);
        this.homeState = homeState;
    }

    public String getHomeState() { return homeState; }
    public void setHomeState(String homeState) {
        this.homeState = homeState;
    }

    public double calculateQuarterlyFees() {
        return 42900 / 3;
    }
}
// DomesticStudent.java
public class DomesticStudent extends Student {

    private String county;

    public DomesticStudent(String name, int age, int perm, String county) {
        super(name, age, perm);
        this.county = county;
    }

    public String getCounty() { return county; }
    public void setCounty(String county) { this.county = county; }

    public double calculateQuarterlyFees() {
        return 13900 / 3;
    }
}

Example using polymorphism with Abstract Methods

// in main
Student[] array = new Student[2];
array[0] = new NonResidentStudent("Richert", 21, 80498567, "Oregon");
array[1] = new DomesticStudent("Zorra", 18, 1234567, "Los Angeles");

for (int i = 0; i < 2; i++) {
    System.out.println(array[i].getName());

    // Abstract methods are visible to Student objects
    // Polymorphism allows the correct calculateQuarterlyFees method to be called.
    System.out.format("%.2f\n",array[i].calculateQuarterlyFees()); // format two decimal places
}