Computers/Language java

week9. Interfaces and Polymorphism

emzei 2011. 4. 10. 19:54

◆ Interfaces vs. Classes

◇ Interface type 

- All methods are abstract : they don't have to implementation

- All methods in an interface type are automatically public

- An interface type does not have instance fields


◈ Interface

: collection of abstract methods

◈ Abstract methods

: methods without body/implementation



◆ Declaring an Interface

public interface InterfaceName

{

       method signatures

}

- don't have instance fields, body

can have constant value (final)



 Implementing an Interface Type

- Use implements reserved word to indicate that a class implements an interface type

public class BankAccount implements Measurable 

  public double 
getMeasure() 
  {

      ...
     return balance; 
  }
}

- A class can implement more one interface type

* Class must declare all the methods that are required by all the interfaces it implements



◆ Converting Between Class and Interface Types

- You can convert from a class type to an interface type, provided the class implements

 BankAccount account = new BankAccount(10000); 
 Measurable x = account; // OK

 Coin dime = new Coin(0.1, "dime"); 
 Measurable x = dime; // Also OK 


- Cannot convert between unrelated types:

 Measurable x = new Rectangle(5, 10, 20, 30); // ERROR

Because Rectangle doesn’t implement Measurable



 Casts ( changing object's type )

- ex.

Add Coin objects to DataSet:

  DataSet coinData = new DataSet(); 
coinData.add(new Coin(0.25, "quarter")); 
coinData.add(new Coin(0.1, "dime")); 
coinData.add(new Coin(0.05, ”nickel")); 
Measurable max = 
coinData.getMaximum(); // Get the largest coin

What can you do with max? It’s not of type Coin:

  String name = max.getName(); // ERROR

You need a cast to convert from an interface type to a class type

You know it’s a Coin, but the compiler doesn’t. Apply a cast:

  Coin maxCoin = (Coin) max; 
String name = 
maxCoin.getName();

If you are wrong and max isn’t a coin, the program throws an exception and terminates
 
Difference with casting numbers:
When casting number types you agree to the information loss
When casting object types you agree to that risk of causing an exception 



◆ Polymorphism (★★★ concept)

- An interface variable holds a reference to object of a class that implements the interface :

Measurable meas;

meas = new BankAccount(10000); 

meas = new Coin(0.1, "dime");

  Note that the object to which meas refers does not have type Measurable

  the type of the object is some class that implements the Measurable interface


- You can call any of the interface methods :

double m = meas.getMeasure();


- When the virtual machine calls an instance method, it locates the method of the implicit parameter's class - calleddynamic method lookup


* If meas refers to a BankAccount object, then meas.getMeasure() calls the BankAccount.getMeasure method


* If meas refers to a Coin object, then method Coin.getMeasure is called


- Polymorphism (many shapes) denotes the ability to treat objects with differences in behavior in a uniform way


◆ Using Interfaces for Callbacks

- Limitations of Measurable interface :

Can add Measurable interface only to classes under your control
Can measure an object in only one way

E.g., cannot analyze a set of savings accounts both by bank balance and by interest rate 


Callback : a mechanism for specifying code that is executed at a later time


- ex.

>>> In previous DataSet implementation, responsibility of measuring lies with the added objects themselves 
Alternative: Hand the object to be measured to a method of an interface:

   public interface Measurer 
 { 
    double measure(Object 
anObject); 
 }

 Object is the “lowest common denominator” of all classes 
The code that makes the call to the callback receives an object of class that implements this interface:

public DataSet(Measurer aMeasurer)

{

   sum = 0;

   count = 0;

   maximum = null;

   measurer = aMeasurer; // Measurer instance variable

}

The measurer instance variable carries out the measurements:

public void add(Object x)

{

   sum = sum + measurer.measure(x);

   if (count == 0 || measurer.measure(maximum) < measurer.measure(x))

      maximum = x;

   count++;

}

A specific callback is obtained by implementing the Measurer interface:

  public class RectangleMeasurer implements Measurer 

   public double measure(Object 
anObject
   { 
      Rectangle 
aRectangle = (Rectangle) anObject
      double area = 
aRectangle.getWidth() *   
         
aRectangle.getHeight(); 
      return area; 
   } 
}

Must cast from Object to Rectangle:

  Rectangle aRectangle = (Rectangle) anObject




 Inner Classes

- Trivial class can be declared inside a method :

public class DataSetTester3

{

   public static void main(String[] args)

   {

      class RectangleMeasurer implements Measurer

      {

         ...

      }

      Measurer m = new RectangleMeasurer();

      DataSet data = new DataSet(m);

      ...

   }

- If inner class is declared inside an enclosing class, but outside its methods, it is available to all methods of enclosing class:

public class DataSetTester3

{

   class RectangleMeasurer implements Measurer

   {

      . . .

   }

   public static void main(String[] args)

   {

      Measurer m = new RectangleMeasurer();

      DataSet data = new DataSet(m);

      . . .

   }

}

- Compiler turns an inner class into a regular class file:

DataSetTester$1$RectangleMeasurer.class 




◆ Mock Objects ( based on interface )

- Want to test a class before the entire program has been completed

- A mock object provides the same services as another object, but in a simplified manner

- ex.

Example: a grade book application, GradingProgram, manages quiz scores using class GradeBook with methods:

public void addScore(int studentId, double score)

public double getAverageScore(int studentId)

public void save(String filename)

Want to test GradingProgram without having a fully functional GradeBook class 

 

Declare an interface type with the same methods that the GradeBook class provides

Convention: use the letter as a prefix for the interface name:

public interface IGradeBook

{

   void addScore(int studentId, double score);

   double getAverageScore(int studentId);

   void save(String filename);

   . . .

}

The GradingProgram class should only use this interface, never the GradeBook class which implements this interface 




◆ Events, Event Sources, and Event Listener

- User interface events include key presses, mouse moves, button clicks, and so on


◇ Event listener

Notified when event happens

Belongs to a class that is provided by the application programmer

Its methods describe the actions to be taken when an event occurs

A program indicates which events it needs to receive by installing event listener objects 

◇ Event source

User interface component that generates a particular event

Add an event listener object to the appropriate event source

When an event occurs, the event source notifies all event listeners 



◆ Processing Timer Events

- timer -> millisecond

javax.swing.Timer generates equally spaced timer events, sending events to installed action listeners

- Useful whenever you want to have an object updated in regular interval

- ex.

Declare a class that implements the ActionListener interface:

  class MyListener implements ActionListener  

   void 
actionPerformed(ActionEvent event) 
   { 
      
 Listener action (executed at each timer event) 
   } 
}

Add listener to timer and start timer:

  MyListener listener = new MyListener(); 
Timer t = new Timer(interval, listener); 
t.start();



 Mouse Events

- Use a mouse listener to capture mouse events

- ex.

Implement the MouseListener interface:

  public interface MouseListener 

   void 
mousePressed(MouseEvent event); 
   // Called when a mouse button has been pressed on a  
   // component 
   void 
mouseReleased(MouseEvent event); 
   // Called when a mouse button has been released on a 
   // component 
   void 
mouseClicked(MouseEvent event); 
   // Called when the mouse has been clicked on a component 
   void 
mouseEntered(MouseEvent event); 
   // Called when the mouse enters a component

     void mouseExited(MouseEvent event); 
   // Called when the mouse exits a component

  } 


***

mousePressedmouseReleased: Called when a mouse button is pressed or released

mouseClicked: If button is pressed and released in quick succession, and mouse hasn’t moved

mouseEnteredmouseExited: Mouse has entered or exited the component’s area 

 


- Call repaint when you modify the shapes that paintComponent draws :

box.setLocation(x, y);

  repaint();


- Mouse listener : if the mouse is pressed, listener moves the rectangle to the mouse location:

  class MousePressListener implements MouseListener 

   public void 
mousePressed(MouseEvent event) 
   { 
      
int x = event.getX(); 
      
int y = event.getY(); 
      
component.moveTo(x, y);

     }

     // Do-nothing methods 
   public void 
mouseReleased(MouseEvent event) {} 
   public void 
mouseClicked(MouseEvent event) {} 
   public void 
mouseEntered(MouseEvent event) {} 
   public void 
mouseExited(MouseEvent event) {} 


'Computers > Language java' 카테고리의 다른 글

week11. Input/Output and Exception Handling  (0) 2011.04.10
week10. Inheritance  (0) 2011.04.10
week8. Graphic User Interface  (0) 2011.04.10
week6. Arrays and Array List  (0) 2011.04.10
week5. Decision  (0) 2011.04.10