public class Point { public double x, y; public Point() {} public Point(double x, double y) { // the parameters x and y are simply the initial // values of field x and y of class Point this.x =x; this.y =y; } public void adjustPosition(....) { x = this.x; y = this.y; // do calculation using the local x and y ... // commit the changes when done this.x = x; this.y = y; } // ... other methods }
static {
value = ...;
}
// ...
}
public interface Comparable { // Compares the executing object to the parameter // returns relative ordering as integer <0, =0, or >0 public int compareTo(Object o); } public interface Iterator { // return true if executing object has one or more objects // that have not been returned by next method yet. public boolean hasNext(); // return a reference to the next object in the iterator public Object next(); //remove item most recently returned by next method from the collection public void remove(); }
class Talking { // reference into a class reference to invoke its unique method. public static void main (String[] args) { // declare an interface reference Speaker current; // instantiates a Dog object using the interface reference current = new Dog(); // invokes one of the common methods current.speak(); // instantiates a philosopher object using the interface reference current = new Philosopher ("I think, therefore I am."); //---> line (*) // invokes the common method current.speak(); // casts the interface to make the Speaker a Philosopher ((Philosopher) current).pontificate(); } }
Note that we cannot just use th dot operator between current and this method, because current is of type Speaker not Philosopher while this method is a member of Philosopher class. Remember, every Philosopher is a Speaker, but not every Speaker is Philosopher. The line (*) makes current a philosopher Speaker, but not a complete Philosopher whcih can invoke any method in Philosopher class. That why the casting is needed.