Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 8: User-Defined Classes and ADTs J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.

Similar presentations


Presentation on theme: "Chapter 8: User-Defined Classes and ADTs J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition."— Presentation transcript:

1 Chapter 8: User-Defined Classes and ADTs J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second Edition

2 Java Programming: From Problem Analysis to Program Design, Second Edition2 Chapter Objectives  Learn about classes.  Learn about private, protected, public, and static members of a class.  Explore how classes are implemented.  Learn about the various operations on classes.

3 Java Programming: From Problem Analysis to Program Design, Second Edition3 Chapter Objectives  Examine constructors and finalizers.  Examine the method toString.  Learn about the abstract data type (ADT).

4 Java Programming: From Problem Analysis to Program Design, Second Edition4 Classes  class : A reserved word; a collection of a fixed number of components.  Components: Members of a class.  Members are accessed by name.  Class members categories/modifiers: –private –Public –protected

5 Java Programming: From Problem Analysis to Program Design, Second Edition5 Classes  Private: Members of class are not accessible outside class.  Public: Members of class are accessible outside class.  Class members: Can be methods or variables.

6 Java Programming: From Problem Analysis to Program Design, Second Edition6 Syntax The general syntax for defining a class is: If a member of a class is a method, it can (directly) access any member of the class—data members and methods. Therefore, when you write the definition of a method (of the class), you can directly access any data member of the class (without passing it as a parameter). The (non-static) data members of a class are called instance variables. The methods of a class are called the instance methods of the class. If a class member is declared/defined without any modifiers, then that class member can be accessed from anywhere in the package.

7 Java Programming: From Problem Analysis to Program Design, Second Edition7 class Clock : Data Members (Instance Variables): private int hr; //store hours private int min; //store minutes private int sec; //store seconds Methods (Instance Methods) : public void setTime(int hours, int minutes, int seconds)//mutator method public int getHours() //accessor method public int getMinutes() //accessor method public int getSeconds() //accessor method public void printTime() public void incrementSeconds() public void incrementMinutes() public void incrementHours() public boolean equals(Clock otherClock) public void makeCopy(Clock otherClock) public Clock getCopy() Syntax

8 Java Programming: From Problem Analysis to Program Design, Second Edition8  Two types of constructors:  With parameters  Without parameters (default constructor )  Constructors have the following properties:  The name of a constructor is the same as the name of the class.  A constructor, even though it is a method, has no type. It is neither a value returning method nor a void method  A class can have more than one constructor. All constructors of a class have the same name.  If a class has more than one constructor, any two constructors must have different signatures.  Constructors are automatically executed when a class object is instantiated. They cannot be called like other methods.  If there are multiple constructors, which constructor executes depends on the type of values passed to the class object when the class object is instantiated. Constructors

9 Java Programming: From Problem Analysis to Program Design, Second Edition9 Default constructor : public Clock(). This constructor initializes the instance variables to set the hours, minutes, and seconds, each to 0. Constructor with parameters: public Clock(int hours, int minutes,int seconds) If you do not include any constructor, java automatically provides the default constructor. Therefore when you create an object, the instance variables are initialized to their default values. Constructors

10 Java Programming: From Problem Analysis to Program Design, Second Edition10 A class and its members can be described graphically using Unified Modeling Language (UML) notation. The + (plus) sign in front of a member indicates that it is a public member; The – (minus) sign indicates that it is a private member. The # symbol before a member name indicates that it is a protected member. Unified Modeling Language Class Diagrams

11 Java Programming: From Problem Analysis to Program Design, Second Edition11 Unified Modeling Language Class Diagrams

12 Java Programming: From Problem Analysis to Program Design, Second Edition12 Variable Declaration and Object Instantiation Clock myClock; Clock yourClock; new className() OR new className(argument1, argument2,..., argumentN)

13 Java Programming: From Problem Analysis to Program Design, Second Edition13 myClock = new Clock(); yourClock = new Clock(9, 35, 15); OR Clock myClock = new Clock(); Clock yourClock = new Clock(9, 35, 15); Variable Declaration and Object Instantiation

14 Java Programming: From Problem Analysis to Program Design, Second Edition14 Variable Declaration and Object Instantiation

15 Java Programming: From Problem Analysis to Program Design, Second Edition15 Accessing Class Members Once an object is created, the object can access the members of the class. The syntax to access a data member of a class object or method is: referenceVariableName.memberName The class members that the class object can access depend on where the object is created. –If the object is created in the definition of a method of the class, then the object can access both the public and private members. –If the object is created elsewhere then the object can access only the public members of the class.

16 Java Programming: From Problem Analysis to Program Design, Second Edition16 Example 8-1 myClock.setTime(5, 2, 30); myClock.printTime(); yourClock.setTime(x, y, z); if (myClock.equals(yourClock)). Accessing Class Members

17 Java Programming: From Problem Analysis to Program Design, Second Edition17 The objects myClock and yourClock can access only public members of the class. Illegal: yourClock.hr = 10; yourClock.min = myClock.min; Accessing Class Members

18 Java Programming: From Problem Analysis to Program Design, Second Edition18 Built-in Operations on Classes Most of Java’s built-in operations do not apply to classes. For example you cannot use the + to add the values of two Clock objects. (, ==) A reference variable uses the dot operator to access public members; Classes can use the dot operator to access public static members.

19 Java Programming: From Problem Analysis to Program Design, Second Edition19 Assignment Operator: A Precaution myClock = yourClock;  Copies the value of the reference variable yourClock into the reference variable myClock. After this statement executes, both yourClock and myClock refer to the same object.

20 Java Programming: From Problem Analysis to Program Design, Second Edition20

21 Java Programming: From Problem Analysis to Program Design, Second Edition21 Assignment Operator: A Precaution Shallow copying: Two or more reference variables of the same type point to the same object. Deep copying: Each reference variable refers to its own object.

22 Java Programming: From Problem Analysis to Program Design, Second Edition22 myClock.makeCopy(yourClock ); : myClock.hr = yourClock.hr; myClock.min = yourClock.min; myClock.sec = yourClock.sec; myClock = yourClock.getCopy(); : create a copy of the object yourClock and returns the address (a reference of the copy). Then stores this address into myClock Assignment Operator: A Precaution

23 Java Programming: From Problem Analysis to Program Design, Second Edition23 makeCopy Both objects must be instantiated before invoking this method getCopy myClock = yourClock.getCopy(); Only the object yourClock must be instantiated before invoking this method Assignment Operator: A Precaution

24 Java Programming: From Problem Analysis to Program Design, Second Edition24 Definitions of the Constructors and Methods of the class Clock When you write the definition of a method of a class and the method uses an object of that class, then within the definition of the method the object can access its private data members (in fact, any private member of the class.)

25 Java Programming: From Problem Analysis to Program Design, Second Edition25 public void setTime(int hours, int minutes, int seconds) { if (0 <= hours && hours < 24) hr = hours; else hr = 0; if (0 <= minutes && minutes < 60) min = minutes; else min = 0; if (0 <= seconds && seconds < 60) sec = seconds; else sec = 0; }

26 Java Programming: From Problem Analysis to Program Design, Second Edition26 Suppose you have created an object myClock. myClock.setTime(3, 48, 52); Definitions of the Constructors and Methods of the class Clock

27 Java Programming: From Problem Analysis to Program Design, Second Edition27 public void incrementSeconds() { sec++; if (sec > 59) { sec = 0; incrementMinutes(); //increment minutes } }

28 Java Programming: From Problem Analysis to Program Design, Second Edition28 public boolean equals(Clock otherClock) { return (hr == otherClock.hr && min == otherClock.min && sec == otherClock.sec); } The method equal is a member of the class clock hr, min, sec are data members of the same class. OtherClock is an object of the class clock. Therefore, the object otherClock can access its private data members within the definition of the method equals.

29 Java Programming: From Problem Analysis to Program Design, Second Edition29 public void makeCopy(Clock otherClock) { hr = otherClock.hr; min = otherClock.min; sec = otherClock.sec; } public Clock getCopy() { Clock temp = new Clock(); temp.hr = hr; temp.min = min; temp.sec = sec; return temp; }

30 Java Programming: From Problem Analysis to Program Design, Second Edition30 myClock.makeCopy(yourClock); myClock = yourClock.getCopy();

31 Java Programming: From Problem Analysis to Program Design, Second Edition31 public Clock() { hr = 0; min = 0; sec = 0; } public Clock() { setTime(0, 0, 0); }

32 Java Programming: From Problem Analysis to Program Design, Second Edition32 public Clock(int hours, int minutes, int seconds) { setTime(hours, minutes, seconds); } public Clock(int hours, int minutes, int seconds) { if (0 <= hours && hours < 24) hr = hours; else hr = 0; if (0 <= minutes && minutes < 60) min = minutes; else min = 0; if (0 <= seconds && seconds < 60) sec = seconds; else sec = 0; }

33 Java Programming: From Problem Analysis to Program Design, Second Edition33 Definition of the class Clock A precondition is a statement specifying the condition(s) that must be true before the function is called. A postcondition is a statement specifying what is true after the function call is completed. In a class definition, it is a common practice to list all the instance variables, named constants, other data members, or variable declarations first, then the constructors, and then the methods.

34 Java Programming: From Problem Analysis to Program Design, Second Edition34 Once a class is properly defined and implemented, it can be used in a program. A program or software that uses and manipulates the objects of a class is called a client of that class.

35 Java Programming: From Problem Analysis to Program Design, Second Edition35 Definition of the class Clock

36 Java Programming: From Problem Analysis to Program Design, Second Edition36 Example 8-2

37 Java Programming: From Problem Analysis to Program Design, Second Edition37 The Copy Constructor Clock myClock = new Clock(8, 45, 22); Clock aClock = new Clock(myClock);  The copy constructor is a special constructor that executes when an object is instantiated and initialized using an existing object.  Syntax of the heading of the copy constructor is : public ClassName(ClassName otherObject)

38 Java Programming: From Problem Analysis to Program Design, Second Edition38 In the definition of the class Clock you have to include: public Clock(Clock otherClock) { hr = otherClock.hr; min = otherClock.min; sec = otherClock.sec; }

39 Java Programming: From Problem Analysis to Program Design, Second Edition39 Example: class Clock

40 Java Programming: From Problem Analysis to Program Design, Second Edition40 The Method toString  Whenever a class is created, Java provides the method toString to the class.  Public value-returning method.  Takes no parameters.  Returns address of a String object.  Output using print, println, printf methods.  Default definition creates String with name of object’s class name followed by hash code of object.

41 Java Programming: From Problem Analysis to Program Design, Second Edition41 The output of the statement: System.out.println(myClock); is: Clock@11b86e7 The Method toString

42 Java Programming: From Problem Analysis to Program Design, Second Edition42 You can override the default definition of the method toString to convert an object to a desired string. public String toString() { String str = “”; if (hr < 10) str = “0”; str = str + hr + “:”; if (min < 10) str = str + “0”; str = str + min + “:”; if (sec < 10) str = str + “0”; str = str + sec; return str; } The Method toString

43 Java Programming: From Problem Analysis to Program Design, Second Edition43 If the values of the instance variables hr, min, sec of myClock are 8, 25, 56. Theen the output of the statement: System.out.println(myClock); is: 08:25:56 The Method toString

44 Java Programming: From Problem Analysis to Program Design, Second Edition44 The Modifier static  In the method heading, specifies that the method can be invoked by using the name of the class.  If used to declare data member, data member invoked by using the class name.  Static data members of class exist even when no object of class type instantiated.  Static variables are initialized to their default values.  For each static data member of the class, Java allocates only one memory space.

45 Java Programming: From Problem Analysis to Program Design, Second Edition45 Example 8-3 public class Illustrate { private int x; private static int y; public static int count; public Illustrate() { x = 0; } public Illustrate(int a) { x = a; } The Modifier static

46 Java Programming: From Problem Analysis to Program Design, Second Edition46 void setX(int a) { x = a; } public String toString() { return("x = " + x + ", y = " + y + ", count = " + count); } public static void incrementY() { y++; } Illustrate illusObject = new Illustrate(); Illustrate.incrementY(); Illustrate.count++; The Modifier static

47 Java Programming: From Problem Analysis to Program Design, Second Edition47 Illustrate illusObject1 = new Illustrate(3); Illustrate illusObject2 = new Illustrate(5); The Modifier static

48 Java Programming: From Problem Analysis to Program Design, Second Edition48 Illustrate.incrementY(); Illustrate.count++; The Modifier static

49 Java Programming: From Problem Analysis to Program Design, Second Edition49 public class StaticMembers { public static void main(String[] args) { Illustrate illusObject1 = new Illustrate(3); //Line 1 Illustrate illusObject2 = new Illustrate(5); //Line 2 Illustrate.incrementY(); //Line 3 Illustrate.count++; //Line 4 System.out.println(illusObject1); //Line 5 System.out.println(illusObject2); //Line 6 System.out.println("Line 7: ***Increment y " + "using illusObject1***"); //Line 7 illusObject1.incrementY(); //Line 8 illusObject1.setX(8); //Line 9 System.out.println(illusObject1); //Line 10 System.out.println(illusObject2); //Line 11 System.out.println("Line 12: ***Increment y " + "using illusObject2***"); //Line 12 illusObject2.incrementY(); //Line 13 illusObject2.setX(23); //Line 14 System.out.println(illusObject1); //Line 15 System.out.println(illusObject2); //Line 16 } }

50 Java Programming: From Problem Analysis to Program Design, Second Edition50 x = 3, y = 1, count = 1 x = 5, y = 1, count = 1 Line 7: ***Increment y usingllusObject1*** x = 8, y = 2, count = 1 x = 5, y = 2, count = 1 Line 12: ***Increment y using illusObject2*** x = 8, y = 3, count = 1 x = 23, y = 3, count = 1 Sample Run

51 Java Programming: From Problem Analysis to Program Design, Second Edition51 A static method cannot use anything that depends on a calling object. In the definition of a static method, you cannot use a non-static data member or a non-static method, unless there is a locally declared object that access the non-static data member or the non-static method The Modifier static

52 Java Programming: From Problem Analysis to Program Design, Second Edition52 Finalizers  Automatically execute when class object goes out of scope.  Have no parameters.  Only one finalizer per class.  Name of finalizer: finalize.

53 Java Programming: From Problem Analysis to Program Design, Second Edition53 Accessor and Mutator Methods  Accessor method: A method of a class that only accesses (that is, does not modify) the value(s) of the data member(s).  Mutator method: A method of a class that modifies the value(s) of the data member(s).

54 Java Programming: From Problem Analysis to Program Design, Second Edition54 Example 8-5 Person Accessor and Mutator Methods

55 Java Programming: From Problem Analysis to Program Design, Second Edition55 Multiple File Programs If a class is to be used in only one program, or if you have divided your program so that it uses more than one class, rather than create a package, you can directly add the file(s) containing the class(es) to the program. multiple-file programs can be managed in the form of a project. A project consists of several files, called the project files.

56 Java Programming: From Problem Analysis to Program Design, Second Edition56 The Reference this  Every object has access to a reference to itself. The name of this reference is the reserved word this.  Refers to instance variables and methods of a class.  Used to implement cascaded method calls.  In a cascaded method call, the result returned by one method (a reference to an object) is used to immediately call another method.

57 Java Programming: From Problem Analysis to Program Design, Second Edition57 public void setTime(int hours, int minutes, int seconds) { if (0 <= hours && hours < 24) this.hr = hours; else this.hr = 0; if (0 <= minutes && minutes < 60) this.min = minutes; else this.min = 0; if (0 <= seconds && seconds < 60) this.sec = seconds; else this.sec = 0; } public void setTime(int hr, int min, int sec) { if (0 <= hr && hr < 24) this.hr = hr; else this.hr = 0; if (0 <= min && min < 60) this.min = min; else this.min = 0; if (0 <= sec && sec < 60) this.sec = sec; else this.sec = 0; }

58 Java Programming: From Problem Analysis to Program Design, Second Edition58 In the class Person public Person setLastName(String last) { lastName = last; return this; } public Person setFirstName(String first) { firstName = first; return this; } In the client program: Person student2 = new Person(); student2.setFirstName("Shelly").setLastName("Malik"); Cascaded method calls

59 Java Programming: From Problem Analysis to Program Design, Second Edition59 student2.setFirstName("Shelly") This expression sets the first name to “Shelly” and returns a reference to the object which is student2, thus the next expression executed is: student2.setLastName("Malik");

60 Java Programming: From Problem Analysis to Program Design, Second Edition60 Abstract Data Types A data type that specifies the logical properties without the implementation details. Such as list An ADT is an abstraction of a commonly appearing data structure, along with a set of defined operations on the data structure. ADT hides the implementation details of the operations and the data from the users of the ADT. Users can use the operations of an ADT without knowing how the operation is implemented.

61 Java Programming: From Problem Analysis to Program Design, Second Edition61 Programming Example: Candy Machine (Problem Statement ) A new candy machine is bought for the gym, but it is not working properly. The machine sells candies, chips, gum, and cookies. In this programming example, we will write a program to create a Java application program for this candy machine so that it can be put into operation.

62 Java Programming: From Problem Analysis to Program Design, Second Edition62 The application program should do the following: 1. Show the customer the different products sold by the candy machine. 2. Let the customer make the selection. 3. Show the customer the cost of the item selected. 4. Accept money from the customer. 5. Release the item. Programming Example: Candy Machine (Problem Statement )

63 Java Programming: From Problem Analysis to Program Design, Second Edition63 ***Welcome to Shelly's Candy Shop *** To select an item, enter 1 for Candy 2 for Chips 3 for Gum 4 for Cookies 9 to exit

64 Java Programming: From Problem Analysis to Program Design, Second Edition64 If you have selected a sold out item Sorry this item is sold out.

65 Java Programming: From Problem Analysis to Program Design, Second Edition65 Please deposit 100 cents: 50 Please deposit 50 cents:50 Collect your item at the bottom and enjoy.

66 Java Programming: From Problem Analysis to Program Design, Second Edition66 Programming Example: Candy Machine (Input and Output)  Input: The item selection and the cost of the item.  Output: The selected item.

67 Java Programming: From Problem Analysis to Program Design, Second Edition67 Programming Example: Candy Machine Components:  Cash register: it has some cash on hand, it accept the amount from the customer, it should show the machine’s owner the amount of money in the register.  Dispenser: it release the selected item if it is not empty. It should show the number of items in it and the cost of the items.  Machine

68 Java Programming: From Problem Analysis to Program Design, Second Edition68 Programming Example: Candy Machine

69 Java Programming: From Problem Analysis to Program Design, Second Edition69 Programming Example: Candy Machine

70 Java Programming: From Problem Analysis to Program Design, Second Edition70 Dispense Chips = new Dispencer(100,65); Programming Example: Candy Machine

71 Java Programming: From Problem Analysis to Program Design, Second Edition71 Programming Example: Candy Machine

72 Java Programming: From Problem Analysis to Program Design, Second Edition72 Programming Example: Candy Machine

73 Java Programming: From Problem Analysis to Program Design, Second Edition73 Programming Example: Candy Machine

74 Java Programming: From Problem Analysis to Program Design, Second Edition74 Programming Example: Candy Machine

75 Java Programming: From Problem Analysis to Program Design, Second Edition75 Chapter Summary  Creating classes  Members of a class:  private  protected  public  static  Implementing classes  Various operations on classes

76 Java Programming: From Problem Analysis to Program Design, Second Edition76 Chapter Summary  Constructors  Finalizers  Method toString  Abstract data types


Download ppt "Chapter 8: User-Defined Classes and ADTs J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition."

Similar presentations


Ads by Google