Lecture Summary 4a

Classes and Interfaces (cont.)


  • The this reference
    Example:
           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 
           }         
    

  • The static modifier
  • Example:   CountInstances.javaMyClass.java,  



  • Inner class
  • Interfaces

  • Polymorphism via Interfaces
    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.



    Applet (continued)