A Class of Our Own We’ve used many classes: –Location –FilledRect –Color –Text –And More! –But what if we want to make our own class?

Slides:



Advertisements
Similar presentations
1 CSC 221: Computer Programming I Fall 2006 interacting objects modular design: dot races constants, static fields cascading if-else, logical operators.
Advertisements

Based on Java Software Development, 5th Ed. By Lewis &Loftus
Python Objects and Classes
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Lecture 2 Basics of C#. Members of a Class A field is a variable of any type that is declared directly in a class. Fields are members of their containing.
CSCI 1100/1202 April 3, Testing A program should be executed multiple times with various input in an attempt to find errors Debugging is the process.
Java Programming Chapter 3 More about classes. Why?  To make classes easier to find and to use  to avoid naming conflicts  to control access  programmers.
CS 106 Introduction to Computer Science I 03 / 21 / 2008 Instructor: Michael Eckmann.
Enhancing classes Visibility modifiers and encapsulation revisited
ObjectDraw and Objects Early Chris Nevison Barbara Wells.
Classes, Encapsulation, Methods and Constructors
Recall: Accessing Location Info private Location firstPoint; public void onMousePress( Location pressPt ) { new Text("Pressed", pressPt, canvas ); firstPoint.
Understanding class definitions Looking inside classes.
The Need for Flexibility Sometimes different classes are really very similar e.g. FramedRect and FramedOval can be moved can check whether a point is inside.
UML Basics & Access Modifier
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Writing Classes (Chapter 4)
Complex objects How might you design a class called NestedRects of graphical objects that look like this? Requirements for the constructor: –Like many.
Overview of our Approach Program Structure –Data, variables, and parameters –Basic control structures (conditionals, loops and Threads) –Class definitions.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Methods with Parameters COMP.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Creating Simple Classes. Outline of Class Account Class Account Account # Balance Holder name phone# Overdrawn (true/false) Data Members Open Credit Debit.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 3: Developing Class Methods Object-Oriented Program Development Using Java: A Class-Centered Approach.
Local Variables Garbage collection. © 2006 Pearson EducationParameters2 of 10 Using Accessors and Mutators Together What if you want to get a property.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
CS0007: Introduction to Computer Programming Classes: Documentation, Method Overloading, Scope, Packages, and “Finding the Classes”
Conditional Statements Consider: if the mouse location is contained in the rectangle, display message “success” Some programming constructs can choose.
Java Decision Making and booleans (Java: An Eventful Approach, Ch 4), Slides Credit: Bruce, Danyluk and Murtagh CS 120 Lecture October 2012.
Computer Science 111 Fundamentals of Computer Programming I Working with our own classes.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Java Object Oriented Programming Encapsulation, Inheritance, Polymorphism (Java: An Eventful Approach - Ch. 17, 21.7), Slides Credit: Bruce, Danyluk and.
Chapter 5 Introduction to Defining Classes
IT108 Objects and Classes Part I George Mason University Revised 4/3/2012.
Graphics Tools and Parameters Chris Nevison Barbara Wells.
SEEM Java – Basic Introduction, Classes and Objects.
Chapter 5 Classes and Methods II Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas, E.
Java Working with Numbers (Java: An Eventful Approach, Ch 3), Slides Credit: Bruce, Danyluk and Murtagh CS 120 Lecture October 2012.
Computer Science I Variables. Methods. Classwork/Homework: Re-do or do new drawing using variables & function(s). Zip folder and upload to Moodle dropbox.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
Chapter 7 Classes and Methods III: Static Methods and Variables Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition)
AP Java Ch. 4 Review Question 1  Java methods can return only primitive types (int, double, boolean, etc).
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
CSE 501N Fall ‘09 03: Class Members 03 September 2009 Nick Leidenfrost.
Comp1004: Building Better Objects II Encapsulation and Constructors.
CSCI 51 Introduction to Programming Dr. Joshua Stough February 26, 2009.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes : Review Java Software Solutions Foundations of Program Design Seventh Edition John.
A structured walkthrough
Computer Science I Variables. Methods.
Chapter 4: Writing Classes
Java Classes (Java: An Eventful Approach, Ch. 6),
Methods The real power of an object-oriented programming language takes place when you start to manipulate objects. A method defines an action that allows.
CS 302 Week 11 Jim Williams, PhD.
Ch 4: Writing Classes Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: Classes and Objects.
Classes, Encapsulation, Methods and Constructors (Continued)
Implementing Non-Static Features
Chapter 4 Writing Classes.
JAVA CLASSES.
Defining Classes and Methods
Classes, Objects and Methods
CS 1054: Lecture 2, Chapter 1 Objects and Classes.
Day 11 The Last Week!.
Presentation transcript:

A Class of Our Own We’ve used many classes: –Location –FilledRect –Color –Text –And More! –But what if we want to make our own class?

What if… We can free ourselves from the limitations of ovals and rectangles and move on to…

A Draggable Face public class RevFaceDrag extends WindowController { private FunnyFace happy;// FunnyFace to be dragged private Location lastPoint; private boolean happyGrabbed = false; // Whether happy has been grabbed by the mouse public void begin() { // Make the FunnyFace happy = new FunnyFace( FACE_LEFT, FACE_TOP, canvas ); } public void onMousePress( Location point ){ lastPoint = point; happyGrabbed = happy.contains( point ); } public void onMouseDrag( Location point ) { if (happyGrabbed ) { happy.move( point.getX() – lastPoint.getX(), point.getY() – lastPoint.getY() ); lastPoint = point; }

Making a Funny Face Physical Characteristics: –Head –Mouth –Two Eyes Behaviors –Can check contains –Movable (by dragging)

Components of a Class Instance Variables Methods Constructors (these are new!)

Instance Variables The data stored in a class Maintain the state of an object Instance variables for FunnyFace: private FramedOval head; private FramedOval mouth; private FramedOval leftEye, rightEye;

Methods Methods: Sections of code executed at certain times: –onMousePress –onMouseDrag –begin Special Types of Methods: –Mutator Methods –Accessor Methods

Actual Parameters Information given to a method when the method is invoked In the invocation of: happy.move (10, 20); –happy is the object –move is the name of the method –the values 10 and 20 are passed to happy.move Order of parameters matters!

A Mutator Method for FunnyFace //Move the entire face by (dx,dy) public void move( double dx, double dy ) { head.move( dx, dy ); leftEye.move (dx, dy ); rightEye.move( dx, dy ); mouth.move( dx, dy ); }

Formal Parameters dx and dy are the formal parameters Formal Parameters: –used in the method declaration –determine the order of actual parameters –determine the type of the actual parameters

Accessor Methods Return information about an object // Determine whether pt is inside FunnyFace public boolean contains( Location pt ) { return head.contains( pt ); }

Constructors A constructor creates an object and initializes relevant instance variables Invoked by the name of the class

public FunnyFace( double left, double top, DrawingCanvas canvas ){ head = new FramedOval( left, top, FACE_WIDTH, FACE_HEIGHT, canvas ); mouth = new FramedOval( left+(FACE_WIDTH-MOUTH_WIDTH)/2, top+2*FACE_HEIGHT/3, MOUTH_WIDTH, MOUTH_HEIGHT, canvas ); leftEye = new FramedOval( left+EYE_OFFSET-EYE_RADIUS/2, top+2*FACE_HEIGHT/3, MOUTH_WIDTH, MOUTH_HEIGHT, canvas ); rightEye = new FramedOval( left+FACE_WIDTH-EYE_OFFSET- EYE_RADIUS/2, top+EYE_OFFSET, EYE_RADIUS, EYE_RADIUS, canvas ); }

Class Convention public class Name { constant definitions variable declarations constructor methods }

Putting it all together Complete source code

Defining Methods Indirectly What if we wanted to move the FunnyFace to a specified location? We can reuse methods already defined public void moveTo( double x, double y ) { this.move( x – head.getX(), y – head.getY() ); }

this public void moveTo( double x, double y ) { this.move( x – head.getX(), y – head.getY() ); } We can use “this” to refer to object itself

What if We want to keep track of the amount of time a FunnyFace was dragged We need an invisible class that keeps track of time…

Timer Class public class Timer { private double startTime; // Time when Timer started or reset public Timer() { // Create timer, initializing startTime with current time startTime = System.currentTimeMillis(); } public double elapsedMilliseconds() { // Number of milliseconds since last reset return System.currentTimeMillis() – startTime; } public double elapsedSeconds() { //Return number of seconds since last reset return this.elapsedMilliseconds() / 1000; } public void reset() { // Reset startTime startTime = System.currentTimeMillis(); }

Using a Timer public class TimedFace{ private Timer stopWatch; public void begin() { // Make the FunnyFace happy = new FunnyFace( FACE_LEFT, FACE_TOP, canvas ); stopWatch = new Timer(); } public void onMousePress( Location point ) { lastPoint = point; happyGrabbed = head.contains( point ); stopWatch.reset(); } public void onMouseDrag( Location point ) { if (happyGrabbed ) { happy.move( point.getX() – lastPoint.getX(), point.getY() – lastPoint.getY() ); lastPoint = point; }

Using a Timer public void onMouseRelease( Location point ){ if(happyGrabbed) { System.out.println( "The Face was dragged for " + stopWatch.elapsedSeconds() + " seconds."); }

Local Variables Recall variables and their uses: –Instance Variables: maintain the state of an object –Formal Parameters: Determine the information required by a method Local Variables: –Declared, initialized and used within a method –Locals do not retain their values between method invocations

Using Local Variables public double elapsedMilliseconds() { // Return number of // milliseconds since last reset double diffTime; diffTime = System.currentTimeMillis() – startTime; return diffTime; } diffTime is a local variable

Using Local Variables To simplify difficult calculations To eliminate redundant computations

Overloading Evaluating gives 12 Evaluating "Good" + " Day" gives "Good Day" + is an overloaded operator: it can add numbers and concatenate strings The type of operation is determined by the types of the operands

Overloading II In Java, users cannot define new overloaded operations We can overload methods!

Overloading III Consider: public void moveTo( double x, double y ) { this.move( x – head.getX(), y – head.getY() ); } And public void moveTo( Location pt ) { this.move( pt.getX() – head.getX(), pt.getY() – head.getY() ); }

Overloading IV What determines when each moveTo is invoked? Answer: The actual parameters moveTo can be invoked either with two doubles or with a Location

Review Components of a class –Instance Variables –Constructors –Methods Formal vs Actual Parameters Instance Variables and Local Variables Overloading