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.

Slides:



Advertisements
Similar presentations
Week 8 Recap CSE 115 Spring Composite Revisited Once we create a composite object, it can itself refer to composites. Once we create a composite.
Advertisements

Computer Science 209 Graphics and GUIs. Working with Color The class java.awt.Color includes constants for typical color values and also supports the.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Inheritance Inheritance Reserved word protected Reserved word super
ITEC200 – Week03 Inheritance and Class Hierarchies.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
1 Inheritance. 2 One class inherits from another if it describes a specialized subset of objects Terminology: inheritschild class subclass –the class.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Interfaces. In this class, we will cover: What an interface is Why you would use an interface Creating an interface Using an interface Cloning an object.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
Graphics Programming with Inheritance Template pattern (Chap 6, se SceneEditor)
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
GUI. Swing Class Hierarchy Swing Components Swing Conatiners  JFrame – top-level window to store components.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
Inheritance and Subclasses in Java CS 21a: Introduction to Computing I Department of Information Systems and Computer Science Ateneo de Manila University.
CPSC 2100 University of Tennessee at Chattanooga – Spring 2013 Object-Oriented Design & Patterns 2 nd edition Cay S. Horstmann Chapter 6: Inheritance and.
Mouse Events. Handling Mouse Events Java provides two listener interfaces to handle mouse events: MouseListener;  MouseListener;  MouseMotionListener.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
Inheritance Horstmann ch , 6.9. Inheritance: basic concepts subclass specializes super class: … extends … inheritance hierarchies overriding method.
CS 11 java track: lecture 4 This week: arrays interfaces listener classes inner classes GUI callbacks.
Java GUI’s are event driven, meaning they generate events when the user interacts with the program. Typical events are moving the mouse, clicking a mouse.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
CS 151: Object-Oriented Design October 24 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
CS 151: Object-Oriented Design September 26 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Copyright © 2002, Systems and Computer Engineering, Carleton University b-Gui2.ppt * Object-Oriented Software Development Part 18-b Building.
Programming in Java CSCI-2220 Object Oriented Programming.
CS 160: Software Engineering October 22 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
Session 18 Chapter 8: Understanding Inheritance. Recall Exercise 2 From Tuesday It’s very annoying to move a target from the pallet and drop it in the.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
MIT AITI 2004 – Lecture 13 Abstract Classes and Interfaces.
CS 151: Object-Oriented Design October 15 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Chapter 5 Introduction to Defining Classes
CS 151: Object-Oriented Design November 5 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Mouse Listeners Moving the mouse will also generate events like the Timer –To have your program respond, you must implement either or both of MouseListener.
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
CS 151: Object-Oriented Design October 1 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
CS Lecture 04 Mice Lynda Thomas
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
CS 180 Problem Solving and Object Oriented Programming Fall 2010 Notes for Week 9: Oct 18-22, 2010 Aditya Mathur Department of Computer Science Purdue.
CS 151: Object-Oriented Design October 29 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Interfaces Describe what classes should do, without specifying how they should do it Not a class, but a set of requirements for classes that want to conform.
Mouse Events GUI. Types of Events  Below, are some of the many kinds of events, swing components generate. Act causing EventListener Type User clicks.
Basic Object-Oriented concepts. Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields –The class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit7: Event-driven programming 1.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Events and Event Handling
Sections Inheritance and Abstract Classes
CMPE 135: Object-Oriented Analysis and Design October 3 Class Meeting
Computer Science 209 Graphics and GUIs.
Inheritance and Polymorphism
Inheritance and Abstract Classes
ITEC324 Principle of CS III
Java Inheritance.
ITEC324 Principle of CS III
CS 151: Object-Oriented Design October 8 Class Meeting
Chapter 6 Inheritance.
Presentation transcript:

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

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.

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; }

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; }

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; }

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. _

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 aSalary > 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. aSalary the new salary aSalary > 0 */ public void setSalary(double aSalary) {... } } Employee e =... ; e.setSalary(50000);

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. _

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 Street

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

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) {... }... }

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

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. _

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. _

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.

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. _

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. _

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

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

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 _

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)

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.

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!

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. _

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())); } } );

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

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.

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

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(); } );