Lecture Summary 4a

Classes and Interfaces (cont.)


  • 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)