Presentation is loading. Please wait.

Presentation is loading. Please wait.

JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation slides for published by Prentice Hall Second Edition.

Similar presentations


Presentation on theme: "JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation slides for published by Prentice Hall Second Edition."— Presentation transcript:

1 JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation slides for published by Prentice Hall Second Edition

2 Java, Java, Java Object Oriented Problem Solving Chapter 2 Objects: Defining, Creating, and Using

3 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Objectives Be familiar with the relationship between classes and objects in a Java program. Be able to understand and write simple programs in Java. Be familiar with some of the basic principles of object-oriented programming. Understand some of the basic elements of the Java language.

4 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Outline Class Definition Case Study: Simulating a CyberPet Object-Oriented Design: Basic Principles Java Language Summary From the Java Library: BufferedReader, String, Integer In the Laboratory: The Circle Class

5 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Class Definition Five basic design questions: –What role will the object perform? –What data or information will it need? –What actions will it take? –What public interface will it present to other objects? –What information will it hide (keep private) from other objects?

6 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects The Rectangle Class A class is a blueprint. It describes an object's form but it has no content. The class contains an object’s method definitions The instance variables, length and width, have no values yet.

7 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects 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; } // Rectangle constructor public double calculateArea() // Access method { return length * width; } // calculateArea } // Rectangle class Instance variables are usually private An object’s public methods make up its interface A public class is accessible to other classes

8 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects The RectangleUser Class The RectangleUser class will create and use 1 or more Rectangle instances. An application has a main() method

9 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects The RectangleUser Class Definition public class RectangleUser { public static void main(String argv[]) { 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()); } // main() } // RectangleUser An application must have a main() method Object Use Object Creation Class Definition

10 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Creating Rectangle Instances Create, or instantiate, two instances of the Rectangle class: The objects (instances) store actual values. Rectangle rectangle1 = new Rectangle(30,10); Rectangle rectangle2 = new Rectangle(25, 20);

11 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Using Rectangle Instances We 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

12 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Define, Create, Use Class definition: Define one or more classes ( Rectangle, RectangleUser ) Object Instantiation: Create objects as instances of the classes ( rectangle1, rectangle2 ) Object Use: Use the objects to do tasks ( rectangle1.calculateArea() )

13 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Design Steps –Problem Specification –Problem Decomposition –Class Design: CyberPet –Method Decomposition –CyberPet Design Specification Case Study: Simulating a CyberPet

14 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Problem Specification Design a program that allows the user to interact with objects that simulate the behavior of a CyberPet. A CyberPet will perform two behaviors, eating and sleeping, when we tell it to.

15 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Problem Decomposition What objects do we need? TestCyberPet serves as a user interface. It creates and uses CyberPets CyberPet objects encapsulate CyberPet state and behavior.

16 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Class Design: CyberPet State: boolean variables, isEating and isSleeping Methods: –A constructor to initialize a CyberPet –An eat method to put pet in eating state –A sleep method to put pet in sleeping state

17 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects CyberPet Class Specification Class Name: CyberPet –Role: To represent and simulate a CyberPet Information Needed (instance variables) –isEating: Set to true when pet is eating (private) –isSleeping: Set to true when pet is sleeping (private) Manipulations Needed (public methods) –CyberPet(): A constructor method to initialize the pet –sleep(): A method to put the pet in sleeping state –eat(): A method to get the pet in eating state

18 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects CyberPet Class Definition public class CyberPet { // Data private boolean isEating = true;// CyberPet's state private boolean isSleeping = false; // Methods public void eat() // Start eating { isEating = true; // Change the state isSleeping = false; System.out.println("Pet is eating"); return; } // eat() public void sleep() // Start sleeping { isSleeping = true; // Change the state isEating = false; System.out.println("Pet is sleeping"); return; } // sleep() } // CyberPet class If no constructor method, Java provides a default.

19 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects The CyberPet Class A class is a blueprint. In this case every CyberPet created will be in the eating state initially. The instance variables, isEating and isSleeping, have initial values.

20 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects public class CyberPet extends Object The Class Header In General: ClassModifiers opt class ClassName Pedigree opt public class CyberPet Example:

21 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Identifiers An identifier is a name for a variable, method, or class. Rule: An identifier in Java must begin with a letter, and may consist of any number of letters, digits, and underscore (_) characters. Legal: CyberPet, eat, sleep, pet1, pet_2 Illegal: Cyber Pet, 30days, pet$, n!

22 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Declaring Instance Variables In General FieldModifiers opt TypeId VariableId Initializer opt Fields or instance variables have class scope. Their names can be used anywhere within the class. Examples: // Instance variables private boolean isEating = true; private boolean isSleeping = false;

23 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Public/Private Access Instance variables should usually be declared private. This makes them inaccessible to other objects. Generally, public methods are used to provide carefully controlled access to the private variables. An object’s public methods make up its interface -- that part of its makeup that is accessible to other objects.

24 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Public/Private Access (cont) Possible Error: Public instance variables can lead to an inconsistent state Example: Suppose we make isEating and isSleeping public variables. george.isEating = true; // Inconsistent george.isSleeping = true; // State The proper way to make george eat: george.eat(); // eat() is public method

25 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Initializer Expressions General Form: Variable = expression The expression on the right of the assignment operator (=) is evaluated and its value is stored in the variable on the left. Examples: private boolean isEating = true; private int petSize = 10; private int petAge = true; // Type error Type error: You can’t assign a boolean value to an int variable

26 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Method Definition Example The Method Header MethodModifiers opt ResultType MethodName (ParameterList ) public static void main (String argv[] ) public void paint (Graphics g) public void init () public void eat () public void MethodName() // Method Header { // Start of method body } // End of method body

27 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Method Definition public void eat() { isEating = true; isSleeping = false; System.out.println("Pet is eating"); return; } // eat() Header: This method, named eat, is accessible to other objects (public), and does not return a value (void). Body: a block of statements that sets the CyberPet’s state to eating.

28 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects 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. 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.

29 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects The Simple Assignment Statement Type error: The value being assigned must be the same type as the variable. isEating = true; isSleeping = false; isEating = 100; // Type error General Form: VariableName = Expression The expression on the right of the assignment operator (=) is evaluated and its value is stored in the variable on the left. Examples:

30 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Creating CyberPet Instances A reference variable refers to an object by storing the address of the object. // Declare a reference variable CyberPet pet1; // Create an instance pet1 = new CyberPet(); (c) After instantiation, pet1 refers to a CyberPet (a) The reference variable, pet1, will refer to a CyberPet (b), but its initial value is null.

31 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Creating CyberPet Instances (cont) Declare and instantiate in one statement: CyberPet pet1 = new CyberPet(); CyberPet pet2 = new CyberPet(); Two CyberPets with names, pet1 and pet2, both eating. UML Object Diagram

32 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Using and Manipulating CyberPets Objects are used by calling one of their public methods: Now pet1 is eating but pet2 is sleeping. pet1.eat(); // Tell pet1 to eat pet2.sleep(); // Tell pet2 to sleep

33 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects The TestCyberPet Class public class TestCyberPet { public static void main (String argv[]) { // Execution starts here System.out.println("main() is starting"); CyberPet pet1; // Declare two references CyberPet pet2; pet1 = new CyberPet(); // Instantiate the references pet2 = new CyberPet(); // by creating new objects pet1.sleep(); // Tell pet1 to sleep. pet1.eat(); // Tell pet1 to eat. pet2.sleep(); // Tell pet2 to sleep. System.out.println("main() is finished"); return; // Return to the system } // main() } //TestCyberPet

34 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects An Applet Interface The TestCyberPetApplet will serve as a user interface for the CyberPet simulation.

35 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects The TestCyberPetApplet Class public class TestCyberPetApplet extends Applet { public void init() { // Execution starts here System.out.println("init() is starting"); CyberPet pet1; // Declare two references CyberPet pet2; pet1 = new CyberPet(); // Instantiate the references pet2 = new CyberPet(); // by creating new objects pet1.sleep(); // Tell pet1 to sleep. pet1.eat(); // Tell pet1 to eat. pet2.sleep(); // Tell pet2 to sleep. System.out.println("init() is finished"); return; // Return to the system } // main() } //TestCyberPetApplet

36 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects CyberPet Application The CyberPet class can be turned into an application by giving it a main() method. Same main() as in TestCyberPet class

37 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Method Call and Return A method call causes a program to transfer control to the first statement in the called method. A return statement returns control to the calling statement.

38 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Tracing TestCyberPet public static void main (String argv[]) { 1 System.out.println("main() is starting"); 2 CyberPet pet1; 3 CyberPet pet2; 4 pet1 = new CyberPet(); 7 pet2 = new CyberPet(); 10 pet1.sleep(); 15 pet1.eat(); 20 pet2.sleep(); 25 System.out.println("main() is finished"); 26 return; } // main() public class CyberPet { 5,8 private boolean isEating = true; 6,9 private boolean isSleeping = false; public void eat() { 16 isEating = true; 17 isSleeping = false; 18 System.out.println("Pet is eating"); 19 return; } // eat() public void sleep() { 11,21 isSleeping = true; 12,22 isEating = false; 13,23 System.out.println("Pet is sleeping"); 14,24 return; } // sleep() } // CyberPet class

39 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Object Oriented Design Encapsulation: The CyberPet class encapsulates a state and a set of actions. Information Hiding: CyberPet’s state is private. Interface: CyberPet’s public methods, eat() and sleep(), limit the way it can be used. Generality/Extensibility: We can easily extend CyberPet’s functionality.

40 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects From the Library: BufferedReader Code Reuse Principle: Before designing and writing your own code, search the Java library for a class that solves your problem. The java.io.BufferedReader class contains methods to perform keyboard I/O. public class BufferedReader extends Reader { public BufferedReader(Reader in); public String readLine(); // Read one line }

41 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Example: Input a String import java.io.*; // Java I/O classes public class Hello // Performs screen I/O { public static void main(String argv[]) throws IOException { BufferedReader input = new BufferedReader (new InputStreamReader(System.in)); System.out.print("Hello, input your name please"); String inputString = input.readLine(); System.out.println("Hello " + inputString); } // main() } // Hello Read one line. Create a reader.

42 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects From the Library: Integer The java.lang.Integer class is a wrapper class that contains methods to convert primitive data into objects and vice versa. The parseInt() method converts a String into an int. Example: Converts “54” into 54 int number = Integer.parseInt( “54”);

43 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Example: Input a Number public class Grader { public static void main(String argv[]) throws IOException { BufferedReader input = new BufferedReader (new InputStreamReader(System.in)); String inputString; int midterm1, midterm2, finalExam; // Three exam grades float sum; // The sum of the 3 grades System.out.print("Input your grade on the first midterm: "); inputString = input.readLine(); midterm1 = Integer.parseInt(inputString); System.out.println("You input: " + midterm1); // Similar code deleted here to input midterm2 and finalExam sum = midterm1 + midterm2 + finalExam; System.out.print("Your average in this course is "); System.out.println(sum/3); } // main() } // Grader Read an integer.

44 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects In the Laboratory: The Circle Class Objectives –To give practice designing a simple Java class to represent a geometric circle. –To convert the design into a working Java program. –To compile, run, and test the Java program. Problem Statement: Design and implement a class to represent a geometric circle, and test your class by implementing a main() method that creates Circle instances and displays their circumferences and areas.

45 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects In the Laboratory (cont) Design: Model your design after the Rectangle class from Chapter 1. Develop a detailed specification. Use comments to document your code. Use stepwise refinement when coding. Sample Output: The diameter of circle1 is 20.0 The area of circle1 is 314.0 The circumference of circle1 is 62.80 The diameter of circle2 is 30.0 The area of circle2 is 706.5 The circumference of circle2 is 94.2

46 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Summary: Technical Terms access modifier assignment statement class scopeescape sequence field declarationfloating point number flow of controlkeyword identifierinitializer expression instance integer interface literal method call and return qualified name void method wrapper class

47 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Summary: Key Points A Java program is a set of interacting objects. A Java class serves as a template for objects. Classes contain instance variables (state) and methods. Java class hierarchy organizes all classes into a single subclass and superclass relationship rooted in Object. A class definition: –header, which names the class and describes its use and pedigree –body, which contains its details. A pedigree describes where it fits in the Java class hierarchy.

48 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Summary: Key Points (cont) A class definition encapsulates the data and methods needed to carry out the class’s task. Design Goals: –W ell-defined purpose –W ell-articulated ( public ) interface –Hidden implementation details (private state) –G eneral and E xtensible. A boolean is a primitive type that can be true or false. Object interface: The public class elements Keyword: a term that has special meaning.

49 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Summary: Key Points (cont) An identifier begins with a letter followed by any number of letters, digits and the underscores (_) and cannot be identical to a keyword. Field declaration (instance variable) –reserves memory within the object –associates a name and type with the location –specifies its accessibility (public or private) Information Hiding: Instance variables should be private. Identifier Scope: Where an identifier can be used. Class scope: Fields and methods can be used anywhere in the class.

50 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Summary: Key Points (cont) Method definition: –Header: names the method and provides other general information –Body: contains its executable statements. Methods that have a return type must return a value of that type. Methods that don’t return a value should be declared void. A method’s formal parameters are variables that are used to bring information into the method.

51 Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects Summary: Key Points (cont) A qualified name is one which involves the dot operator (.) and is used to refer to an object's methods and instance variables. Declaring a reference variable creates a name for an object but doesn't create the object itself. Instantiating a reference variable creates an object and assigns the variable as its name or reference. Execution of a Java application begins with the first statement in the body of the main() method.


Download ppt "JAVA, JAVA, JAVA Object-Oriented Problem Solving Ralph Morelli Trinity College Hartford, CT presentation slides for published by Prentice Hall Second Edition."

Similar presentations


Ads by Google