a) mySphere.displayStatistics() calls area() in Sphere and myBall.displayStatistics() calls area in Ball. Whenever a method is overridden in a derived class, objects of the derived class used the overridden method.
b)
Sphere s1 = new Sphere();
Ball b1 = new Ball();
s1.displayStatistics(); //calls area() in Sphere because s1 refers to a Sphere
object
s1 = b1;
s1.displayStatistics(); // calls area() in Ball because s1 refers to a Ball
object
b1.displayStatistics(); // calls area() in Ball because b1 refers to a Ball
object
abstract class Person { private String _name;
abstract public int yearsExperience();
public Person(String name) { _name = name; }
public String getName() { return _name; }
public void setName(String name) { _name= name; }
} class Student extends Person { private int _year;
public Student(String name, int year) { super(name); _year = year; }
public int yearsExperience() { return _year; }
public void setYear(int year) { _year = year; } } class GraduateStudent extends Student { private String _thesisTitle;
public GraduateStudent(String name, int year, String thesisTitle) { super(name, year); _thesisTitle = thesisTitle; }
public void setThesisTitle(String title) { _thesisTitle = title; }
public String getThesisTitle() { return _thesisTitle; } } |
// Note, jdk Interface List and class LinkedList are used instead of the // book's ListInterface and ListReferenceBased. import java.util.LinkedList; import java.util.List; public class SortedList implements SortedListInterface { private List<Comparable> aList;
public SortedList() { aList = new LinkedList(); }
public int size() { return aList.size(); }
public boolean isEmpty() { return aList.isEmpty(); }
public void removeAll() { aList.clear(); }
public void sortedAdd(Comparable newItem) throws ListException { for (int i = 0; i < aList.size(); i++) { if (newItem.compareTo(aList.get(i)) <= 0) { aList.add(i, newItem); return; } } aList.add(newItem); }
public Comparable get (int index) throws IndexOutOfBoundsException { return aList.get(index); }
public int locateIndex(Comparable anItem) { return aList.indexOf(anItem); }
public void sortedRemove(Comparable anItem) throws ListException { // Note, this is not the most efficient implementation because // it iterates all the way through the list for an item that // is not found aList.remove(anItem); }
public static void main(String[] args) { SortedList list = new SortedList();
list.sortedAdd("Smith"); list.sortedAdd("Zacheral"); list.sortedAdd("Jones"); list.sortedAdd("Anthony"); list.sortedAdd("Baker"); list.sortedAdd("Osterman");
for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i)); } } } |