Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. Copyright 2003, Csturner, adapted from notes.

Similar presentations


Presentation on theme: "Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. Copyright 2003, Csturner, adapted from notes."— Presentation transcript:

1 Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. csturner@csc.calpoly.edu805-756-6133 Copyright 2003, Csturner, adapted from notes and Koffman, Wolz text. Copyright © 2000 by C Scheftic. All rights reserved. Used by permission. These notes do rely heavily on ones originally developed  by John Lewis and William Loftus to accompany  by John Lewis and William Loftus to accompany D Java Software Solutions © Addison-Wesley  by Ralph Morelli to accompany  by Ralph Morelli to accompany D Java Java Java © Prentice-Hall and  by Mark Hutchenreuther for CSC-101 at Cal Poly, SLO  by Mark Hutchenreuther for CSC-101 at Cal Poly, SLO D © Mark Hutchenreuther

2 CPE-101Objectives D Understand the concept of a class hierarchy. D Be familiar with the relationship between classes and objects in a Java program. D Be able to understand and write simple programs in Java. D Be familiar with some of the basic principles of object- oriented programming. D Understand some more of the basic elements of the Java language.

3 CPE-101Objects D An object has: state - descriptive characteristics state - descriptive characteristics behaviors - what it can do (or can be done to it) behaviors - what it can do (or can be done to it) D Example: a coin that can be flipped so it's face shows either "heads" or "tails" One state of the coin is its current face (heads or tails). One state of the coin is its current face (heads or tails). One behavior of the coin is that it can be flipped. One behavior of the coin is that it can be flipped. Note that the behavior of the coin might change its state! Note that the behavior of the coin might change its state!

4 CPE-101 Another Object D An object has: state - descriptive characteristics state - descriptive characteristics behaviors - what it can do (or can be done to it) behaviors - what it can do (or can be done to it) D Another example: a ball The state of the ball is defined by data (the value of certain variables), such as: The state of the ball is defined by data (the value of certain variables), such as: n surface — dimpled n color — white n size — small n elasticity — firm The behavior of the ball is defined by methods (functions), such as: The behavior of the ball is defined by methods (functions), such as: n Hit( )Roll( )Bounce( ) Throw( ) Once again, the behavior of the ball might change its state. Once again, the behavior of the ball might change its state.

5 CPE-101 Interacting Objects D Illustration of interacting objects: the interface for an automated software-ordering program.

6 CPE-101 Interacting Objects  The applet object gets data (“Joseph Smith”) from the customerNameField object and passes it to the orderForm object. applet Customer NameField orderForm “Joseph Smith” Give me your value! The customer’s name is “Joseph Smith”

7 CPE-101Classes D A class is a blueprint of an object. Other comparisons: a model, pattern, or template Other comparisons: a model, pattern, or template D Objects are created from such blueprints. D For a group of like objects, a class defines their common data and methods. It merely defines them. It merely defines them. It does not create them, nor allocate memory space for their data. It does not create them, nor allocate memory space for their data.

8 CPE-101 Object Instantiation D An object is an instance of a class. When an object is declared, then memory is set aside for the data associated with that particular instance of the class. When an object is declared, then memory is set aside for the data associated with that particular instance of the class. D Each object has its own data. Thus, each object has its own state. Thus, each object has its own state. D Each object shares its behavior with other objects of its class. Thus, objects share the methods of the class. Thus, objects share the methods of the class.

9 CPE-101Classification D A hierarchy chart shows a classification of objects: Animal InvertebrateVertebrate MammalFishReptile HorseDogCat

10 CPE-101 The Java Class Hierarchy (partial) Object Component GridLayout BorderLayout Button TextField Label TextComponent TextArea Container Panel Window java.awt Key Class Abstract Class Extends

11 CPE-101 Classes Used Already Name some classes we have used already. D Some were provided by Java, including: String String System System Math Math Applet Applet D Next we will learn to write our own classes! Read the examples in our textbook Read the examples in our textbook In class, we will do one of our own: Rectangle In class, we will do one of our own: Rectangle

12 CPE-101 Class Definition D Five basic design questions: What tasks will the object perform? What tasks will the object perform? What information will it need to perform its tasks? What information will it need to perform its tasks? What methods will it use to process its information? What methods will it use to process its information? What information will it make public for other objects? What information will it make public for other objects? What information will it hide from other objects? What information will it hide from other objects?

13 CPE-101Classes D A class contains data declarations, and data declarations, and method declarations method declarations int x, y; char ch; Data declarations Method declarations

14 CPE-101 Data Scope D The scope of data is: the area in a program in which the area in a program in which that data can be used (referenced). that data can be used (referenced). D Data declared at the class level: can be used by all methods in that class. can be used by all methods in that class. D Data declared within a method: can only be used in that method; can only be used in that method; is called local data. is called local data.

15 CPE-101 Writing Methods A method declaration specifies the code that will be executed when the method is invoked (or called). D When a method is invoked, the flow of control jumps to the method and jumps to the method and executes its code. executes its code. D When complete, the flow returns to the place where the method was called and returns to the place where the method was called and continues. continues. D Depending on how the method was defined, the invocation may return a value, or may return a value, or may not return a value. may not return a value.

16 CPE-101 myMethod(); myMethodcompute Method Control Flow D The called method could be within the same class, in which case only the method name is needed

17 CPE-101 doIt helpMe helpMe(); obj.doIt(); main Method Control Flow D The called method could be part of another class or object

18 CPE-101 The Class Definition The Rectangle Class Definition public class Rectangle { private double length; // Instance variables private double width; public Rectangle(double l, double w) // Constructor method { length = l; width = w; } // end Rectangle constructor public double calculateArea() // Access method { return length * width; } // end calculateArea } // end Rectangle class An object’s public methods make up its interface A public class is accessible to other classes Instance variables are usually private

19 CPE-101 The Class The Rectangle Class D A class is a blueprint. It describes an object's form, but It describes an object's form, but it has no content. (cf “static”) it has no content. (cf “static”) The instance variables, length and width, have no values yet. The class contains an object’s method definitions A Rectangle length width Rectangle(l,w) calculateArea()

20 CPE-101 Instance Data  The length and width variables in the Rectangle class are called instance data because each instance (object) of the Rectangle class has its own. A class declares the type of the data, but it does not reserve any memory space for it A class declares the type of the data, but it does not reserve any memory space for it Every time a Rectangle object is created, new length and width variables are created as well. Every time a Rectangle object is created, new length and width variables are created as well. D The objects of a class share the method definitions, but they have unique data space. That's the only way two separate objects can have different states. That's the only way two separate objects can have different states.

21 CPE-101 Rectangle rectangle1 = new Rectangle(30, 10); Rectangle rectangle2 = new Rectangle(25, 20); A Rectangle 10 30 length width Rectangle(l,w) calculateArea() A Rectangle 20 25 length width Rectangle(l,w) calculateArea() rectangle1rectangle2 The objects (instances) store actual values. Creating Instances Creating Rectangle Instances D Create, or instantiate, two instances of the Rectangle class:

22 CPE-101 Interacting with a Interacting with a Rectangle D We can use a method call to ask each object to tell us its area: rectangle1 area 300 rectangle2 area 500 Printed output: System.out.println("rectangle1 area " + rectangle1.calculateArea() ); System.out.println("rectangle2 area " + rectangle2.calculateArea() ); References to objects Method calls

23 CPE-101Encapsulation You can take one of two views of an object: D internal: the structure of its data, the algorithms used by its method D external: the interaction of the object with other objects in the program From this view, an object is an encapsulated entity, providing a set of specific services. From this view, an object is an encapsulated entity, providing a set of specific services. These services define the interface to the object. These services define the interface to the object. Recall that an object is an abstraction, hiding details from the rest of the system when that is useful to do. Recall that an object is an abstraction, hiding details from the rest of the system when that is useful to do.

24 CPE-101 Encapsulation (continued) An object should be self-governing. D Any changes to the object's state (its variables) should be accomplished by that object's methods. D It should be difficult, if not impossible, for an object to "reach in" and alter another object's state. D The user, or client, of an object can request its services, but it should not have to be aware of how those services are accomplished.

25 CPE-101 Encapsulation (illustrated) D An encapsulated object can be thought of as a black box. D Its inner workings are hidden from the client, which can only invoke the interface methods. Client Methods Data

26 CPE-101 public class Rectangle // Class Header { // Start class body } // End class body D In General: ClassModifiersopt class ClassName Pedigreeopt ClassModifiersopt class ClassName Pedigreeopt public class Rectangle extends Object public class Rectangle extends Object D Example: The Class Header

27 CPE-101 Visibility Modifiers D In Java, we accomplish encapsulation through the appropriate use of visibility modifiers. D A modifier is a Java reserved word that specifies particular characteristics of a method or data value.  We've used another modifier, final, to define a constant. D Java has three visibility modifiers: public public private private protected protected

28 CPE-101 Visibility Modifiers D Members of a class that are declared with public visibility can be accessed from anywhere. D Members of a class that are declared with private visibility can only be accessed from inside the class. D Members declared without a visibility modifier have default visibility and can be accessed by any class in the same package. D When you learn about inheritance, you will then learn about the use of protected visibility. D Java modifiers are discussed in detail in Appendix F D In 101, we will use only the public and private modifiers.

29 CPE-101 Visibility Modifiers D As a general rule, no object's data should be declared with public visibility. Instance variables should usually be declared private. This makes them inaccessible to other objects. Public instance variables can lead to an inconsistent state…. Instance variables should usually be declared private. This makes them inaccessible to other objects. Public instance variables can lead to an inconsistent state…. D Public methods are also called service methods. Methods that provide the object's services are usually declared with public visibility so that they can be invoked by clients. Methods that provide the object's services are usually declared with public visibility so that they can be invoked by clients. An object’s public methods make up its interface; they are used to provide carefully controlled access to the private variables. An object’s public methods make up its interface; they are used to provide carefully controlled access to the private variables. D A method created simply to assist a service method is called a support method. Since a support method is not intended to be called by a client, it should not be declared with public visibility. Since a support method is not intended to be called by a client, it should not be declared with public visibility.

30 CPE-101 Declaring Instance Variables D In General FieldModifiers opt TypeId VariableId Initializer opt FieldModifiers opt TypeId VariableId Initializer opt D Fields or instance variables have class scope. Their names can be used anywhere within the class. D Example (from an unidentified class): // Instance variables private boolean isEating = true; private boolean isSleeping = false;

31 CPE-101 Problem Decomposition Reconsider Rectangle : What objects do we need?  The Rectangle class: represents a rectangle and represents a rectangle and implements the calculateArea command. implements the calculateArea command.  We will also need a RectangleUser class to serve as a user interface. Create one or more instances of a Rectangle (here, two) and Create one or more instances of a Rectangle (here, two) and Let the user interact with them (here, assign them dimensions and print out their areas). Let the user interact with them (here, assign them dimensions and print out their areas).

32 CPE-101 Class Design: Rectangle D State: double variables, length and width double variables, length and width D Methods: A constructor to initialize a Rectangle A constructor to initialize a Rectangle A calculateArea method to determine the rectangle’s area A calculateArea method to determine the rectangle’s area

33 CPE-101 Rectangle Class Specification  Class Name: Rectangle Task: To represent a rectangle Task: To represent a rectangle D Information Needed (instance variables) length : A measure of one side of the rectangle (private) length : A measure of one side of the rectangle (private) width : A measure of a perpendicular side of the rectangle (private) width : A measure of a perpendicular side of the rectangle (private) D Manipulations Needed (public methods) Rectangle() : A constructor method to initialize the rectangle Rectangle() : A constructor method to initialize the rectangle calculateArea() : A method to calculate the area from the length and width calculateArea() : A method to calculate the area from the length and width

34 CPE-101 Designing Methods  The public methods serve as a class’s interface.  If a method is intended to be used to communicate with or pass information to an object, it should be declared public. D A class’s methods have class scope. They can be used anywhere within the class.  Methods that do not return a value should be declared void.

35 CPE-101 Method Definition D Example D The Method Header MethodModifiers opt ResultType MethodName ( FormalParameterList ) public static void main (String [ ] args ) public void paint (Graphics g) public void init ( ) public void flip ( ) public double calculateArea ( ) public void MethodName( ) // Method Header { // Start of method body } // End of method body

36 CPE-101 Method Definition public double calculateArea() // Access method { return length * width; } // end calculateArea Header: This method, named calculateArea, is accessible to other objects (public), and does return a value (of type double). Body: a block of statements that performs the calculateArea of a Rectangle.

37 CPE-101 The RectangleUser Class public class RectangleUser { public static void main (String[ ] args) { Rectangle rectangle1 = new Rectangle(30,10); Rectangle rectangle2 = new Rectangle(25,20); System.out.println("rectangle1 area " + rectangle1.calculateArea()); System.out.println("rectangle2 area " + rectangle2.calculateArea()); } // end main() } // end RectangleUser An application must have a main( ) method Object Use Object Creation Class Definition

38 CPE-101 Creating a Rectangle Instance Rectangle rect1; // Declare a reference variable rect1 = new Rectangle(6,4); // Create an instance The reference variable, rect1, will refer to a Rectangle, but its initial value is null. rect1 After instantiation, rect1 refers to a specific Rectangle object. A Rectangle 4 6 length width Rectangle(l,w) calculateArea()

39 CPE-101 A Rectangle 4 6 length width Create 2 Rectangle Instances (cont) D Declaration and instantiation in one statement: rect1 Two Rectangles, with names, rect1 & rect2, with different shapes but both will produce an area of 24. A Rectangle 8 3 length width rect2 Rectangle rect1 = new Rectangle(6, 4); Rectangle rect2 = new Rectangle(3, 8); Rectangle(l,w) calculateArea() Rectangle(l,w) calculateArea()

40 CPE-101 Method Call and Return D A method call causes a program to transfer control to the first statement in the called method. D A return statement returns control to the calling statement. method1() method2(); method2() statement1 ; return ; nextstatement;

41 CPE-101 Define, Create/Instantiate, Use D Class Definition: Define one or more classes Rectangle, RectangleUser Rectangle, RectangleUser D Object Instantiation: Create objects as instances of the classes rectangle1, rectangle2 rectangle1, rectangle2 D Object Use: Use the objects to do tasks rectangle1.calculateArea( ) rectangle1.calculateArea( )

42 CPE-101 Object Oriented Design  Encapsulation: The class encapsulates a state and a set of actions.  Encapsulation: The Rectangle class encapsulates a state and a set of actions.  Information Hiding: state is private.  Information Hiding: Rectangle state is private.  Interface: public access method,, limits the way it can be used.  Interface: Rectangle public access method, calculateArea( ), limits the way it can be used.  Generality/Extensibility: We can easily extend the functionality of.  Generality/Extensibility: We can easily extend the functionality of Rectangle.


Download ppt "Chapter 3: OOD and Writing Worker Classes Clark Savage Turner, Ph.D. Copyright 2003, Csturner, adapted from notes."

Similar presentations


Ads by Google