1 / 76

Chapter 8: User-Defined Classes and ADTs

Chapter 8: User-Defined Classes and ADTs. J ava P rogramming: From Problem Analysis to Program Design, Second Edition. Chapter Objectives. Learn about classes. Learn about private , protected , public , and static members of a class. Explore how classes are implemented.

mccannm
Download Presentation

Chapter 8: User-Defined Classes and ADTs

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 8: User-Defined Classes and ADTs JavaProgramming: From Problem Analysis to Program Design, Second Edition

  2. 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. Java Programming: From Problem Analysis to Program Design, Second Edition

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

  4. 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 Java Programming: From Problem Analysis to Program Design, Second Edition

  5. 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. Java Programming: From Problem Analysis to Program Design, Second Edition

  6. 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. Java Programming: From Problem Analysis to Program Design, Second Edition

  7. 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 Java Programming: From Problem Analysis to Program Design, Second Edition

  8. Constructors • 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. Java Programming: From Problem Analysis to Program Design, Second Edition

  9. Constructors • Default constructor : • publicClock(). • 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. Java Programming: From Problem Analysis to Program Design, Second Edition

  10. Unified Modeling Language Class Diagrams 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. Java Programming: From Problem Analysis to Program Design, Second Edition

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

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

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

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

  15. 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. Java Programming: From Problem Analysis to Program Design, Second Edition

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

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

  18. 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. Java Programming: From Problem Analysis to Program Design, Second Edition

  19. 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. Assignment Operator: A Precaution Java Programming: From Problem Analysis to Program Design, Second Edition

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

  21. 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. Java Programming: From Problem Analysis to Program Design, Second Edition

  22. Assignment Operator: A Precaution 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 Java Programming: From Problem Analysis to Program Design, Second Edition

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

  24. 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.) Java Programming: From Problem Analysis to Program Design, Second Edition

  25. 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; } Java Programming: From Problem Analysis to Program Design, Second Edition

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

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

  28. 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. Java Programming: From Problem Analysis to Program Design, Second Edition

  29. 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; } Java Programming: From Problem Analysis to Program Design, Second Edition

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

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

  32. 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; } Java Programming: From Problem Analysis to Program Design, Second Edition

  33. Definition of the class Clock • A precondition isa statement specifying the condition(s) that must be true before the function is called. • A postcondition is astatement 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. Java Programming: From Problem Analysis to Program Design, Second Edition

  34. 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. Java Programming: From Problem Analysis to Program Design, Second Edition

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

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

  37. 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) Java Programming: From Problem Analysis to Program Design, Second Edition

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

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

  40. 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. Java Programming: From Problem Analysis to Program Design, Second Edition

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

  42. The Method toString 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; } Java Programming: From Problem Analysis to Program Design, Second Edition

  43. The Method toString 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 Java Programming: From Problem Analysis to Program Design, Second Edition

  44. 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. Java Programming: From Problem Analysis to Program Design, Second Edition

  45. The Modifier static 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; } Java Programming: From Problem Analysis to Program Design, Second Edition

  46. The Modifier static 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++; Java Programming: From Problem Analysis to Program Design, Second Edition

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

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

  49. 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 }} Java Programming: From Problem Analysis to Program Design, Second Edition

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

More Related