Download presentation
Presentation is loading. Please wait.
Published byLorena Georgiana Morrison Modified over 9 years ago
1
CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak www.cs.sjsu.edu/~mak
2
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 2 Invoking a Superclass Method Suppose a manager’s salary is his regular employee salary plus a bonus that only managers get. public class Manager extends Employee { public double getSalary() { return salary + bonus; // ERROR--private field }... } public double getSalary() { return getSalary() + bonus; // ERROR--recursive call } A subclass cannot access private fields of its superclass.
3
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 3 Invoking a Superclass Method Use the super keyword. Turns off polymorphism. super is not a reference. public double getSalary() { return super.getSalary() + bonus; }
4
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 4 Invoking a Superclass Constructor Use the super keyword by itself in the subclass constructor to call the superclass constructor. Must be the first statement in the subclass constructor. Pass any required parameters. If a subclass constructor doesn’t explicitly call a superclass constructor, the superclass’s default constructor (the one without parameters) is called. Therefore, then the superclass must have a default constructor. Otherwise, the subclass constructor must call super(). public Manager(String aName) { super(aName); // calls superclass constructor bonus = 0; }
5
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 5 Invoking a Class’s Own Constructor A class can invoke its own constructor (from another constructor) by calling this : public Manager(String aName) { super(aName); // calls superclass constructor bonus = 0; } public Manager(String aName, double aBonus) { this(aName); // must be the first statement bonus = aBonus; }
6
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 6 Preconditions and Inheritance Recall that a precondition of a method is a condition that must be true before the method can be called. The caller is responsible for making sure the precondition is true before making the call. Suppose a subclass overrides a superclass method. The precondition of the subclass method cannot be stronger than the precondition of the overridden superclass method. _
7
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 7 Preconditions and Inheritance Suppose in Manager class’s override of setSalary(), we set @precondition aSalary > 100000 What if variable e referred to a Manager object? Then the manager’s precondition is violated but the programmer has no way to check it when writing the code. public class Employee { /** * Sets the employee salary to a given value. * @param aSalary the new salary * @precondition aSalary > 0 */ public void setSalary(double aSalary) {... } } Employee e =... ; e.setSalary(50000);
8
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 8 Postconditions and Inheritance When a subclass overrides a method, the method’s postcondition must be at least as strong as the postcondition of the superclass method. Suppose Employee.setSalary() has a postcondition that it does not decrease the employee’s salary. Then Manager.setSalary() must have a postcondition that is at least as strong (such as increase the manager’s salary). Other conditions: When you override a method, you cannot make it less visible. Example: If a superclass method is public, you cannot override the method in a subclass and make it private. An overridden method cannot throw more checked exceptions than are declared in the superclass method. _
9
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 9 Favor Composition over Inheritance Class hierarchies should not be complex! Don’t have over 5 or 6 levels. Otherwise, programmers may get lost in the hierarchy. “Has a” (aggregation) is often more flexible than “is a” (inheritance) Use aggregation or composition to reduce the number of levels in the class hierarchy and to add flexibility. PersonWithAddress Person ProfessorStudent Person ProfessorStudent Address StreetEmail
10
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 10 Why Favor Composition Over Inheritance? An example of the Java library getting it wrong: What’s wrong with this design? Oops: public class Stack extends Vector { T pop() {... } void push(T item) {... }... } Stack st = new Stack (); st.push("A"); st.push("B"); st.push("C"); st.remove(1); // Remove "B" in a non-stack way
11
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 11 Why Favor Composition Over Inheritance? The Stack class should have used aggregation instead of inheritance: Now you can’t call remove() on a stack object. _ public class Stack { private Vector elements; T pop() {... } void push(T item) {... }... }
12
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 12 Superclasses and Interfaces CS151, CS153, and CS160 each “is a” Course. Course is the superclass. CS151, CS153, and CS160 each extends Course. CS151, CS153, and CS160 each implements Online. Online is an interface type. What are the differences between extending a class and implementing an interface? Course CS151CS153CS160 «interface» Online CS151CS153CS160
13
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 13 Differences Between Classes and Interfaces Class (“concrete” not abstract) Can contain fields. It must implement any methods that it contains. Subclasses can override the methods. A class has only one superclass (default: the Object class). Interface Can contain fields, but they must be constants. It does not implement any methods that it declares. Classes that implements the interface must implement each of the interface’s declared methods. A class can implement zero, one, or more interfaces. _
14
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 14 “Implements” A class implements an interface. A class extends a superclass. A class implements a method by providing its code. A Java interface type does not implement the methods that it declares. _
15
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 15 What is an Abstract Class? An abstract class is declared with the abstract keyword. Example: public abstract class Food {... } It may or may not contain any abstract methods. If a class has at least one abstract method, then the class itself must be declared abstract. An abstract method is like a method of an interface. It has no implementation. In an abstract class, you must explicitly declare an abstract method with the abstract keyword. Example: public abstract void cook(... ); A subclass of an abstract superclass must implement each of the superclass’s abstract methods.
16
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 16 Purpose of an Abstract Class Unlike an interface, an abstract class can implement some or all of its methods. Therefore, like any other superclass, an abstract class can contain common functionality for its subclasses. An abstract class forces its subclasses to implement certain methods by declaring those methods to be abstract. Any subclass of the abstract class must implement each of the abstract methods. Similar: Any class that implements an interface must implement each of the interface’s methods. _
17
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 17 Important Facts about Abstract Classes An abstract class cannot be instantiated. You cannot create an object directly from an abstract class. Therefore, if you do not want a class to be instantiated, just declare it abstract even if it does not contain any abstract methods. A variable’s type can be an abstract class. It can refer to an object instantiated from a “concrete” subclass of the abstract class. In UML class diagrams, the name of an abstract class and the name of an abstract method is in italics. _
18
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 18 Abstract Class Example Chicken void prepare() void cook() void serve() Broccoli void prepare() void cook() void serve() PorkChops void prepare() void cook() void serve() Food Food createFood(int type,...) void prepare() void cook() void serve() Food food = Food.createFood(type,...); food.prepare(); food.cook(); food.serve(); Factory methodAbtract base classAbstract methods Abstract type Concrete object Concrete classes
19
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 19 Abstract Class Example Each subclass of the abstract Food class must implement the abstract prepare(), cook(), and serve() methods. Chicken void prepare() void cook() void serve() Broccoli void prepare() void cook() void serve() PorkChops void prepare() void cook() void serve() Food Food createFood(int type,...) void prepare() void cook() void serve()
20
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 20 Mouse Events How do you get a Swing component such as a panel to respond to mouse events? Mouse clicks which button x and y coordinates of the click Mouse motion current x and y coordinates of the mouse pointer drags x and y coordinates of where the mouse entered and exited Mouse wheel wheel moved _
21
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 21 Mouse Events The panel wants to listen to mouse events. Mouse event listener Mouse motion listener Mouse wheel listener EventMethod enter mouseEntered(MouseEvent e) exit mouseExited(MouseEvent e) button pressed mousePressed(MouseEvent e) button released mouseReleased(MouseEvent e) button clicked mouseClicked(MouseEvent e) EventMethod move mouseMoved(MouseEvent e) drag mouseDragged(MouseEvent e) EventMethod wheel moved mouseWheelMoved(MouseWheelEvent e)
22
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 22 Mouse Adapter Interfaces MouseEventListener, MouseMotionListener, and M ouseWheelListener together declare a number of methods. What if you’re only interested in a few mouse events, say only mouse pressed and mouse dragged? Do you still have to implement all the other methods? Abstract class MouseAdapter implements all three interfaces and therefore it implements all their methods. However, it implements each method to do nothing. Create a subclass of MouseAdapter and only override the methods you care about. The remaining methods will inherit doing nothing.
23
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 23 Mouse Adapter public abstract class MouseAdapter implements MouseListener, MouseMotionListener, MouseWheelListener { // Mouse event listener public void mouseClicked(MouseEvent event) {} public void mousePressed(MouseEvent event) {} public void mouseReleased(MouseEvent event) {} public void mouseEntered(MouseEvent event) {} public void mouseExited(MouseEvent event) {} // Mouse motion listener mouseMoved(MouseEvent e) {} mouseDragged(MouseEvent e) {} // Mouse wheel listener mouseWheelMoved(MouseWheelEvent e) {} } Do nothing!
24
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 24 Mouse Adapter Suppose we have a JPanel object that’s only interested in listening to mouse button press and a mouse drag events. Create two anonymous classes that each extends the MouseAdapter abstract class. Override the mousePressed() and mouseDragged() methods. Each overrides the default “do nothing” behavior in MouseAdapter in order to do something useful for the application. _
25
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 25 Mouse Adapter mousePanel.addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent event) { eventLabel.setText("Pressed"); buttonLabel.setText(BUTTONS[event.getButton()]); countLabel.setText(String.valueOf(event.getClickCount())); xLabel.setText(String.valueOf(event.getX())); yLabel.setText(String.valueOf(event.getY())); } } );
26
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 26 Mouse Adapter mousePanel.addMouseMotionListener(new MouseAdapter() { public void mouseDragged(MouseEvent event) { eventLabel.setText("Dragged"); countLabel.setText(String.valueOf(event.getClickCount())); xLabel.setText(String.valueOf(event.getX())); yLabel.setText(String.valueOf(event.getY())); } } ); Demo
27
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 27 Car Dragging Demo Recall our original car demo that animated a car using a timer. We embedded drawing a car shape inside the paintIcon() method of a subclass of Icon. For this new demo, we’ll embed drawing a car shape in the paintComponent() method of a subclass of JComponent. The advantage of using a subclass of JComponent is that we inherit all the features of that superclass. In particular, our JComponent subclass will inherit listening to mouse events. Events we are interested in: mouse button pressed mouse dragged Therefore, we will use the abstract MouseAdapter class.
28
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 28 Car Dragging Demo The application will allow us to use the mouse to drag a car shape within a frame. Store the point where the mouse button went down inside the car shape in field mousePoint. addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent event) { mousePoint = event.getPoint(); if (!car.contains(mousePoint)) { mousePoint = null; } ); Demo
29
SJSU Dept. of Computer Science Fall 2013: October 31 CS 151: Object-Oriented Design © R. Mak 29 Car Dragging Demo Drag the car by tracking the mouse. addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent event) { if (mousePoint == null) return; Point lastMousePoint = mousePoint; mousePoint = event.getPoint(); double dx = mousePoint.getX() - lastMousePoint.getX(); double dy = mousePoint.getY() - lastMousePoint.getY(); car.translate((int) dx, (int) dy); repaint(); } );
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.