29
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

CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

Embed Size (px)

Citation preview

Page 1: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

CS 151: Object-Oriented Design October 31 Class Meeting

Department of Computer ScienceSan Jose State University

Fall 2013Instructor: Ron Mak

www.cs.sjsu.edu/~mak

Page 2: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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 accessprivate fields of its superclass.

Page 3: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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; }

Page 4: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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;}

Page 5: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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;}

Page 6: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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._

Page 7: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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);

Page 8: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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._

Page 9: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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

Professor Student

Person

Professor Student

Address

Street Email

Page 10: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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<T> extends Vector<T>{ T pop() { ... } void push(T item) { ... } ...}

Stack<String> st = new Stack<String>();st.push("A");st.push("B");st.push("C");st.remove(1); // Remove "B" in a non-stack way

Page 11: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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<T>{ private Vector<T> elements;

T pop() { ... } void push(T item) { ... } ... }

Page 12: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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 classand implementing an interface?

Course

CS151 CS153 CS160

«interface»Online

CS151 CS153 CS160

Page 13: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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.

_

Page 14: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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._

Page 15: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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.

Page 16: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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._

Page 17: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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._

Page 18: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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 method

Abtract base class

Abstract methods

Abstracttype

Concreteobject

Concreteclasses

Page 19: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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()

Page 20: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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

_

Page 21: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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

Event Method

enter mouseEntered(MouseEvent e)

exit mouseExited(MouseEvent e)

button pressed mousePressed(MouseEvent e)

button released mouseReleased(MouseEvent e)

button clicked mouseClicked(MouseEvent e)

Event Method

move mouseMoved(MouseEvent e)

drag mouseDragged(MouseEvent e)

Event Method

wheel moved mouseWheelMoved(MouseWheelEvent e)

Page 22: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 2013: October 31

CS 151: Object-Oriented Design© R. Mak

22

Mouse Adapter

Interfaces MouseEventListener, MouseMotionListener, and MouseWheelListener 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.

Page 23: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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!

Page 24: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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._

Page 25: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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())); } });

Page 26: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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

Page 27: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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.

Page 28: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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

Page 29: CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak mak

SJSU Dept. of Computer ScienceFall 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(); } });