






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The concept of abstract classes in Java with an example of an abstract Account class and its subclass Fee. It also explains interfaces in Java with the help of an example of the Comparable interface. The Comparable interface is used to sort objects and is demonstrated with an Ingredient class example.
Typology: Slides
1 / 11
This page cannot be seen from the preview
Don't miss anything!







CS108, Stanford Handout # Fall, 2008-09 Osvaldo Jiménez
Thanks to Nick Parlante for much of this handout
Here we look at a variety of more advanced inheritance issues.
units 10
s
units 10
s2 yot 2
Grad
Student
public abstract class Account { /* Applies the end-of-month charge to the account. This is "abstract" so subclasses must override and provide a definition. At run time, this will "pop down" to the subclass definition. */ protected abstract void endMonthCharge();
public void endMonth() { // Pop down to the subclass for their // specific charge policy (abstract method) endMonthCharge();
transactions = 0; } ...
// Fee.java public class Fee extends Account { public void endMonthCharge() { withdraw(5.00); } ...
class Food { boolean same(Food food) { ...
class Candy extends Food { private int sugar;
// incorrect override .. Candy arg more narrow than Food boolean same(Candy candy) { // Treat candy like a Candy object in here return (this.sugar == candy.sugar); }
Java Interface
// Moodable.java public interface Moodable { public Color getMood(); // interface defines getMood() prototype but no code
}
public class Student implements Moodable {
public Color getMood() { if (getStress()>100) return(Color.red); else return(Color.green); } // rest of Student class stuff as before...
Moodable m = s; // Moodable can point to a Student m.getMood(); // this works m.getStress(); // NO does not compile
public interface Comparable { public int compareTo (Object other); }
// Ingredient.java import java.util.*;
/**
public class Ingredient implements Comparable
/**
/**
/**
/**
/**
"name (grams-value grams)"/**
// Standard equals() tests... if ( this == obj) return true ; if (!(obj instanceof Ingredient)) return false ;
// Now do deep compare Ingredient other = (Ingredient)obj; return (grams==other.getGrams() && name.equals(other.getName())); }
/**
/**
/**
... sections showing typical client code.