Presentation is loading. Please wait.

Presentation is loading. Please wait.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 3 Designing.

Similar presentations


Presentation on theme: "© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 3 Designing."— Presentation transcript:

1 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 3 Designing Classes Bret Ford © 2005, Prentice Hall

2 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The Java Interface An interface is a pure abstract classlike structure. An interface is a pure abstract classlike structure. Contains only public abstract methods and public final static data. Contains only public abstract methods and public final static data. Classes implement the interface rather than extending it. Classes implement the interface rather than extending it. Serves as a template for its implementing classes. Serves as a template for its implementing classes.

3 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The Java Interface (concluded) Interface reference variables can be assigned references from any implementing class. Interface reference variables can be assigned references from any implementing class. Calling a method with an interface reference variable invokes polymorhpism. Calling a method with an interface reference variable invokes polymorhpism. An interface may be implemented by more than one class. An interface may be implemented by more than one class.

4 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Declaring an Interface Use the keyword interface. Example: | public interface InterfaceName { public static final DATA_NAME = ; // method declaration uses only a signature public returnType methodName( ); } Use the keyword interface. Example: | public interface InterfaceName { public static final DATA_NAME = ; // method declaration uses only a signature public returnType methodName( ); }

5 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing an Interface The relationship between a class and an interface is established by using the keyword implements. The relationship between a class and an interface is established by using the keyword implements. The implementing class must provide method declarations for each method in the interface. The implementing class must provide method declarations for each method in the interface. // class interface declaration public class ClassName implements InterfaceName { }

6 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The Measurement Interface The Measurement interface is a template for the definition of geometric classes that define the area and perimeter of shapes. The Measurement interface is a template for the definition of geometric classes that define the area and perimeter of shapes. public interface Measurement { public static final double PI = ; double area(); double perimeter(); }

7 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. public class Circle implements Measurement { private double radius; // creates an instance with // the specified radius public Circle(double radius) { this.radius = radius; } // interface method area() returns // PI * radius (squared) public double area() { return PI * radius * radius; } // interface method perimeter() returns // 2 * PI * radius public double perimeter() { return 2 * PI * radius; } Circle Class

8 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. // access and update methods public double getRadius() { return radius; } public void setRadius(double radius) { this.radius = radius; } // returns a description of the object public String toString() { return "Circle with radius " + radius; } } Circle Class (concluded)

9 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. UML for the Measurement Hierarchy

10 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Using an Interface Type An interface reference variable can be assigned any object from a class that implements the interface, and polymorphism applies. An interface reference variable can be assigned any object from a class that implements the interface, and polymorphism applies. InterfaceName ref; ImplementingClass obj = new ImplementingClass(...); ref = obj; // calls methodName() in ImplementingClass ref.methodName();

11 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. public static void resize(Measurement m, double pct) { if (m instanceof Rectangle) { // cast m as a Rectangle Rectangle r = (Rectangle)m; // use setSides() to resize the // length and width r.setSides(r.getLength()*pct, r.getWidth()*pct); }resize()

12 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. else if (m instanceof Circle) { // cast m as a Circle Circle c = (Circle)m; // use setRadius() to resize the radius c.setRadius(c.getRadius()*pct); } resize() (concluded)

13 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Interface Inheritance Hierarchy A parent interface may be used to derive a child interface. Use the extends keyword. A parent interface may be used to derive a child interface. Use the extends keyword. Example: public interface DiagonalMeasurement extends Measurement { public double diagonal(); } public class Circle implements DiagonalMeasurement { }

14 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Extending Interface Implementations A class that implements an interface can be extended. The subclass implements the interface also. A class that implements an interface can be extended. The subclass implements the interface also. Example: public class Rectangle implements Measurement {... } public class Square extends Rectangle {

15 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Multiple Interfaces and Inheritance Java only allows a class to extend one superclass (single inheritance). Java only allows a class to extend one superclass (single inheritance). Some languages like C++ allow a class to inherit multiple superclasses. Some languages like C++ allow a class to inherit multiple superclasses.

16 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Multiple Interfaces and Inheritance (continued)

17 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Java Answer to Multiple Inheritance Allow a superclass to implement multiple interfaces. Allow a superclass to implement multiple interfaces.

18 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc Documentation is needed with any programming language. Documentation is needed with any programming language. The javadoc utility produces HTML documentation for classes and interfaces. The javadoc utility produces HTML documentation for classes and interfaces.

19 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc (continued) Javadoc comments begin with the marker /** and end with the marker */ Javadoc comments begin with the marker /** and end with the marker */ Can use HTML tags in a javadoc comment. Can use HTML tags in a javadoc comment. Javadoc tags that produce HTML include: Javadoc tags that produce HTML for a for a method return method return exception thrown when an error exception thrown when an error occurs

20 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc Example /** * The Circle class provides measurement * operations for objects that are determined by their radius. */ public class Circle implements Measurement {/** * Creates a circle with the specified radius radius the radius of this object IllegalArgumentException if the argument * is negative. */ public Circle(double radius) {... } /** * Returns the area of the circle. a double having value PI *r (squared). */ public double area() {... } }

21 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc Output for Circle Class

22 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc Output for Circle Class (continued)

23 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc Output for Circle Class (continued)

24 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc Output for Circle Class (continued)

25 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Javadoc Output for Circle Class (continued)

26 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Design Pattern Documents the solution to a problem in a very general way. Documents the solution to a problem in a very general way. Singleton design pattern describes a model for building a class that may only have one instance. Singleton design pattern describes a model for building a class that may only have one instance.

27 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. public class Dice { // static reference that identifies // the single instance private static Dice dice = null; private Random rnd; private int dice1, dice2; // private constructor is called by // the method getDice() to create // a single instance of the class private Dice() { // create the random number generator rnd = new Random(); } Dice Class as Example of Singleton Design Pattern

28 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. // if no object currently exists, the // method calls the private constructor // to create an instance; in any case, the // method returns the static reference // variable dice public static Dice getDice() { if (dice == null) { dice = new Dice(); } return dice; } Dice Class as Example of Singleton Design Pattern (continued)

29 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. // toss the dice and update values // for dice1 and dice2 public void toss() { dice1 = rnd.nextInt(6) + 1; dice2 = rnd.nextInt(6) + 1; } // access methods getOne(), getTwo(), // and getTotal()... } Dice Class as Example of Singleton Design Pattern (continued)

30 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. GUI Application Design GUI = "Graphical User Interface". GUI = "Graphical User Interface". GUI Components GUI Components Frame - Main application window Frame - Main application window Panel - Container to which other components are added Panel - Container to which other components are added Label - Displays a string and/or an image Label - Displays a string and/or an image Text field - Allows input/output of text line Text field - Allows input/output of text line Button - Responds to pressing with mouse Button - Responds to pressing with mouse

31 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Key Components of a GUI Application

32 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Inheritance Hierarchy for Java GUI Components

33 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. GUI Application Design Pattern public class DiceToss extends JFrame { public static void main(String[] args) { DiceToss app = new DiceToss(); app.setVisible(true); } // constructor creates components and adds them to the frame public DiceToss() { } // inner class defines an event handler object private class EventHandler implements { } }

34 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. GUI Design Pattern Import Statements Import statements specify the class libraries that the application will use Import statements specify the class libraries that the application will use import java.awt.*;// original Java AWT import javax.swing;// Swing component classes import java.awt.event.*;// Java event classes and interfaces

35 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. GUI Design Pattern Application Variables Declare as application variables the GUI components and any data that will be accessed by event handlers, utility methods, and inner classes. Declare as application variables the GUI components and any data that will be accessed by event handlers, utility methods, and inner classes.

36 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Dice Class Variables class DiceToss extends JFrame { // application variables private JPanel panelA, panelB; private JLabel dieLabel1, dieLabel2, totalLabel; private JTextField totalField; private JTextArea totalArea; private JButton tossButton; private Dice d = Dice.getDice(); private ImageIcon[] diePict = {null, new ImageIcon("die1.gif"), new ImageIcon("die2.gif"), new ImageIcon("die3.gif"), new ImageIcon("die4.gif"), new ImageIcon("die5.gif"), new ImageIcon("die6.gif")};... }

37 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. GUI Application Constructor Initializes frame properties and loads the components. Initializes frame properties and loads the components. Set title with setTitle(titleStr). Set title with setTitle(titleStr). setBounds(posX, posY, width, height) sets the size of the frame and its position on the screen. setBounds(posX, posY, width, height) sets the size of the frame and its position on the screen. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) closes the frame and exits the application when the user clicks the close box in the frame. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) closes the frame and exits the application when the user clicks the close box in the frame.

38 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. GUI Application Constructor (concluded) Components in a frame reside in a region called the content pane. Components in a frame reside in a region called the content pane. Use getContentPane() to access the content pane and assign it to a Container reference variable. Container content = getContentPane(); Use getContentPane() to access the content pane and assign it to a Container reference variable. Container content = getContentPane(); Create and organize components and add them to the content pane. Create and organize components and add them to the content pane.

39 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. public DiceToss() {... // establish the content pane for the window Container content = getContentPane(); content.setLayout(new BorderLayout()); // panel and labels for the two die pictures JPanel panelA = new JPanel(); dieLabel1 = new JLabel(); dieLabel2 = new JLabel(); panelA.add(dieLabel1); panelA.add(dieLabel2); // text area to store results of // successive dice tosses totalArea = new JTextArea(10, 15); DiceToss Constructor

40 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. // panel with toss button, total label, // and text field for the total // the toss button has an action listener // (see next section) JPanel panelB = new JPanel(); tossButton = new JButton("Toss"); tossButton.addActionListener(new TossEvent()); totalLabel = new JLabel("Total"); totalField = new JTextField(4); panelB.add(tossButton); panelB.add(totalLabel); panelB.add(totalField); DiceToss Constructor (continued)

41 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. // add panels and individual components to the // content pane using compass point constants // for class BorderLayout. // the text area is embedded in a JScrollPane // to add scroll bars content.add(panelA, BorderLayout.NORTH); content.add(new JScrollPane(totalArea), BorderLayout.CENTER); content.add(panelB, BorderLayout.SOUTH); } DiceToss Constructor (concluded)

42 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Event Listeners An event is an action such as a mouse click, a button press, or a keystroke. An event is an action such as a mouse click, a button press, or a keystroke. An event listener is an object that resides in a component and waits for the occurrence of an event and handles the actions required by the event. An event listener is an object that resides in a component and waits for the occurrence of an event and handles the actions required by the event. Add a listener to a component using where Type is the type of the event. Add a listener to a component using addTypeListner(...) where Type is the type of the event.

43 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Action Events An event which indicates that a component-defined action occurred. This event is generated by a component (such as a Button) when the component-specific action occurs (such as being pressed). The event is passed to every ActionListener object that registered to receive such events using the component's addActionListener method An event which indicates that a component-defined action occurred. This event is generated by a component (such as a Button) when the component-specific action occurs (such as being pressed). The event is passed to every ActionListener object that registered to receive such events using the component's addActionListener method

44 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Action Events (continued) Adds action listener to a component. The parameter is the event handler that responds to the event. void addActionListener(ActionListener handlerObj) Adds action listener to a component. The parameter is the event handler that responds to the event. Normally use a private inner class to define an event handler. An inner class has access to all the variables in the outer class and can update them. Normally use a private inner class to define an event handler. An inner class has access to all the variables in the outer class and can update them.

45 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Action Events (concluded) An action listener event handling class must implement the ActionListener interface. The interface has only one method Invoked when an action occurs An action listener event handling class must implement the ActionListener interface. The interface has only one method void actionPerformed(ActionEvent ae) Invoked when an action occurs

46 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Action Event Sequence

47 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. private class TossEvent implements ActionListener { public void actionPerformed(ActionEvent ae) { d.toss(); dieLabel1.setIcon(diePict[d.getOne()]); dieLabel2.setIcon(diePict[d.getTwo()]); totalArea.append("Total is " + d.getTotal() + "\n"); totalField.setText("" + d.getTotal()); } DiceToss Event Handler Class


Download ppt "© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 3 Designing."

Similar presentations


Ads by Google