1 / 120

Chapter 8 Creating and Using Model Classes

Chapter 8 Creating and Using Model Classes. Go. Section 1 - The Structure of a Model Class Section 2 - Details about Objects and Model Classes Section 3 - The Client - Server Relationship and the Model/View Pattern Section 4 - More about Model Classes

ishort
Download Presentation

Chapter 8 Creating and Using Model Classes

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 8Creating and Using Model Classes Go Section 1 - The Structure of a Model Class Section 2 - Details about Objects and Model Classes Section 3 - The Client - Server Relationship and the Model/View Pattern Section 4 - More about Model Classes Section 5 - Inheritance, Superclasses and Subclasses Section 6 - More About Methods and Parameters Section 7 - Activation Records and the Scope and Life Time of Variables Section 8 - GUI Program Examples: Images, Mouse Operations Go Go Go Go Go Go Go 1

  2. Chapter 8 Objectives • Design and implement a simple model class from user requirements. • Organize a program with two files that includes a view class and a model class. • Use visibility modifiers (public and private) to make methods visible to clients and restrict access to data within a class. 2

  3. Chapter 8 Objectives (cont.) • Write appropriate mutator methods, accessor methods, and constructors for a class. • Understand how parameters transmit data to methods. • Use global instancevariables, local variables, and parameters appropriately in both model classes and view classes. • Utilize private helper methods in model classes when it is appropriate. 3

  4. Chapter 8 Vocabulary Here are some of the terms you will become familiar with in Chapter 8: • Identity • Instantiation • Lifetime • Mutator • Scope • State • Visibility modifier • Accessor • Actual parameter • Behavior • Constructor • Encapsulation • Formal parameter • Helper method 4

  5. Section 1The Structure of a Model Class 5

  6. 8.1 Model Classes Define Objects Programmers write model classes when they want to define a particular kind of object. Each object of a model class may have many variables associated with it. As an instance (object of the model class) is constructed, each one of the instance variables of the object is given a default value or initialized to some other value. This actually saves an incredible amount of time, because a programmer would have to declare all of the variables separately in a program for what would represent an object and what if you had a large number of them? It would take an incredible amount of time. Constructing objects is faster and much more efficient! 6

  7. 8.1 Constructors of a Model Class Just like a cookie cutter can cut out the same kind of cookie (like a gingerbread man) over and over again, a model classis a template that can construct the same kind of object over and over again. If we cut out gingerbread men with a cookie cutter, we could give some red eyes and some green eyes, but they would all have eyes. They would have other characteristics also in common and they all could be customized to our liking. In Java, if you use the default constructor of a model class, then all of the objects have exactly the same characteristics. If we were making gingerbread men that might be all red eyes with white frosting for their belts. However, if we use the initializing constructor of a model class, then we can initialize the values of the object to what we want! 7

  8. 8.1 Instance Variables of a Model Class The instance variables of an object represent the specific characteristics that an object has. For an example, a Person may have a name, age, address, and phone number. So values for a Person object can be stored in the Person object’s instance variables. Instance variables of a model class are always declared as private. What this means is that other classes in other files cannot directly access those instance variables. In Java and other object-oriented languages, we design model classes so that those value must be accessed indirectly through methods. These methods are called accessor methods. 8

  9. 8.1 Accessor & Mutator Methods By calling an accessor method, you can obtain the value stored in an instance variable of the object. So, an accessor method must be declared as public so other classes in other files can call the method when needed. This is a safe way of operating, because an instance variable can’t accidentally be changed if it is made private. If it was made public, it could be accidentally changed because we could directly access it. If an instance variable needs to be changed, then we can explicitly do that by calling a mutator method. A mutator method is a safe way to change an instance variable, because we know we would never want to call the method unless we fully intended on changing the value of an instance variable. 9

  10. 8.1 The Public & Private Visibility Modifiers In Java and other programming languages, the visibility modifierspublic and private are used to determine what code in files have access to. Essentially, public means that methods, variables, and constants that are declared public can be seen, or are visible, by the code in other files. The word private means that methods, variables, and constants that are declared private CANNOT be seen, or are INVISIBLE, by the code in other files. The details of this you will understand the more you work with classes and understand the principle of information hiding. 10

  11. 8.1 The toString Method The state of an object is the values the instance variables of the object hold at a certain moment of time. So if we want to get the state of an object, then we can call the toString method. The toString method is a method that has a standard method signature that never changes. This method signature exactly matches the method signature of the toString method in the Object class. By writing a toString method with the method signature: public String toString ( ) we are overloading the toString method of the Object class. There are reasons we want to overload this method and you will understand more about that as we go along. 11

  12. 8.1 The Object Class The Object class is sometimes referred to as the “mother” of all classes in Java, because all classes descend from it. They descend from it because a hierarchy exists that has the Object class automatically at the top of the hierarchy. Object Class Person Class We draw the arrow upward to signify that the Person class inherits from the Object class. Here, Object is the superclass and Person is the subclass. 12

  13. 8.1 The Structure of a Model Class Generally, the convention of most programmers is to place the elements of a model class in the following order: Package declarations and Import Statements Class definition line Global Private instance variables Constructor methods Accessor methods Mutator methods toString() method 13

  14. 8.1 The Structure of a Class Template Let’s look at the structure of a model class by inspecting the elements of the Person class. This file will be sent you. Later on, you will learn what chaining is and how to use the Java reserved word this. 14

  15. Section 2Details about Objectsand Model Classes 15

  16. 8.2 What is an Object? • An object is a run-time entity that contains data and responds to messages. • Run-time entity means that … an object exists only when a program is “running”. • More specifically, an object exists only from the time it is constructed in a method until the method is over or until it is sent to garbage collection. (Note: if the method stops and calls another method, then the method is not over. It is just temporarily suspended so the object is temporarily suspended unless an alias is passed to the method being called.) 16

  17. 8.2 What is a Model Class? • A modelclass is a software package or template that describes the characteristics of similar objects. We could also think of it as a “cookie cutter”. Just like a cookie cutter “stamps out” cookies, a model class “stamps out” objects because it is a template. • Two characteristics of an object are: • Data - instance variablesthat define an object’s data components, in other words, data is stored in these variables.We also call instance variables fields. • Behavior - methodsthat define an object’s behavior when a message is sent to it to perform an operation. 17

  18. 8.2 The Behavior of an Object We said that methods define an object’s behavior. So you can think of behavior like this … when an object of a model class calls a method, we like to say that we are sending a message to that object. However, when we send an object a message, we are actually asking it to perform an operation (some behavior) that uses the data stored in itself … not some other object. So the object that is being sent the message is being told“how to behave” or “what to do” based on the data it contains. 18

  19. 8.2 Encapsulation • Encapsulation is combining data and behavior into a single software component called an object. • The instance variables of an object hold the data for the object and those values can change at any instance when a program is running. The current values of the data of an object is called thestate of the object. • We call an object … an instance of a class. Even though it lasts longer than an instant. It can change instantly when a method is called. 19

  20. 8.2 What is Instantiation? • Instantiation is the process of creating a new object through constructing it. An instantiated object of a class is referred to as an instance of the class. We can create many instances of a class during a program. Each instance exists as long as the part of the program that created it and is using it is running. 20

  21. 8.2 Some Classes are NOT Model Classes Some classes are not model classes, but ratherdriver programs. You’ve learned that you can have console programs with a main() method or they may be applets programs like Rocket. These programs don’t “stamp out” any objects. They are not templates for creating objects. However, technically in Java, they create one object and that is the object that is the program itself, but again, they are not really a template for creating numerous objects. We sometimes call these driver programs view files or client files. 21

  22. 8.2 Model & Driver Classes Person Model Class with Constructors Accessors Mutators & toString Methods defines a Person object PersonDriver Class with main method Calls Constructors Calls Accessors Calls Mutators & Calls toString Methods uses Person objects 22

  23. 8.2 How a Program maintains Objects When a Java program begins to run, RAM memory is allocated to hold: • All class templates - the compiled code of all model classes being used so that objects can be instantiated when needed. • Space for variables and objects in any program file, in particular, for a driver file where objects are generally constructed. (Memory for instance variables of an object are allocated within the overall memory allocated for the object.) Summarizing … instances of a class (objects) appear and occupy memory when instantiated. Instances disappear when they are no longer needed ... meaning the memory is freed up through garbage collection so that it can be reused. All RAM memory used by a program is freed up when it stops running. 23

  24. 8.2 The Identity of an Object We’ve already mentioned two of the characteristics of an object and now we mention a third … identity. • Behavior (methods) • State (data values of the instance variables) • Identity (the unique ID that an instance of the class has based on its location in RAM memory - its memory address) If an object doesn’t have an identity, then Java couldn’t distinguish between two different objects of the same model class and where they are located in memory. The JVM establishes the identity of any instance of a class when it is constructed and RAM memory is allocated for its storage. 24

  25. person1 8.2 Conceptualizing Objects Memory for data is allocated within the memory allocated for an object. A Person object has 4 pieces of data: name, age, address, and phone. Memory is allocated to hold the separate values for each instance variable, depending on their data type when the object is instantiated (constructed). Person person1 = new Person(); name = “” age = 0 address = “” phone = “” person1 is a variable that knows the address in RAM memory of where the object is stored. 25

  26. 8.2 The JVM Keeping Track of Objects • The JVM knows if an object is in use by keeping track of whether or not there are any variables referencing it. For example, the JVM knows whether there is a variable like person1 which references the Person object we just saw. • Because unreferenced objects cannot be used, Java assumes that it is okay to delete them from memory using a process called garbage collection. This is done automatically in Java but not in C++ where programmers have to write the code to return memory allocated for an object back to the system when the instance is not needed anymore. If this isn’t done then RAM memory can fill up when a lot of data is manipulated. 26

  27. Section 3The Client - Server RelationshipandThe Model - View Pattern 27

  28. 8.3 The Client - Server Relationship • When a message is sent to an object of a model class (meaning that we use an object to call one of the methods in its model class), two things are involved: • The sender (the client or view file) … usually a driver class calls a public method of the model class using the object. • The receiver (the server or model file) … executes the request of the client file by executing one of its methods and possibly sending a value back to the client file. • Client: • A client’s interactions with a server are limited to sending it public messages, because it can’t access its private instance variables. • A client needs to know only a servers interface, that is, the list of methods that can be called that are supported by the server. 28

  29. 8.3 The Client - Server Relationship To picture this relationship, we could list the classes this way into the categories they fit into: Server - Model - Receiver Client - View - Sender - Driver Person.java PersonDriver.java Student.java StudentAp.java Auto.java AutoDriver.java Car.java JavaCar.java 29

  30. 8.3 The Model-View Pattern Many Java programs use this model-view pattern to divide up the responsibility of different parts of a program into separate files. We call this theserver-client organization. The responsibilities of the model class are handling “modeling an object”, in other words the specifics of creating objects and having them respond to messages from a client file. The responsibilities of the view class are to decide when objects need to be created, when messages need to be sent to them, and “controlling the view” of the program. The advantage is that someone can make different kinds of driver programs, like console programs or applet programs and change the view without changing the model class. 30

  31. 8.3 Information Hiding Information hiding is when we don’t know what the code is in a model class, but we know how to call methods of the model class to manipulate an instance of the class. The class may also be a class like the Math class that really isn’t a model class, where we don’t know what code was written to calculate the square root of a number, like the sqrt() method. This means that the client programmer only knows the method signatures of the methods in the server class, which tells them how to call the methods to construct objects and send messages to them. You don’t need to know the code inside a method to call it properly. You only need to know its method signature! 31

  32. Section 4More About Model Classes 32

  33. For a client programmer to use objects in a driver file, he or she only needs to know a model class’ interface. The interface is simply a listing of the public constructors and public methods of the model class. Here is the Student interface: // Constructor thatinitializes a Student object to default values public Student ( ) // Constructor thatinitializes a Student object’s name and three test scores public Student (String nm, int t1, int t2, int t3) // Constructor that copies the Student object s into a new Student object. public Student (Student s) // Retrieves the name stored in the Student object. public String getName ( ) // Retrieves the test score in the Student object designated by the parameter i. publicint getScore (int i) (continued next slide) 8.4 Using A Model Class Interface 33

  34. 8.4 The Student Class Interface Continued (interface continued) // Modifies the name of a Student object. publicvoid setName (String nm) // Modifies a particular Student's test score. publicvoid setScore (int i, int score) // returns the average of a Student object's test scores. publicdouble getAverage ( ) // returns the highest test score of a Student object'sthree test scores. publicint getHighScore ( ) // returns the STATE of a Student object. public String toString() The interface is all a client programmer needs to know! 34

  35. 8.4 Visibility Modifiers private and public are visibility modifiers. They define whether a method or instance variable can be seen by other classes. Instance variables should always be made private. This promotes safety and information hiding. One way a programmer doesn’t have access to any of the code of a model class is when they are sometimes given to programmers in jar files that cannot be opened but can be added to the “build path” of a program so they can be used. They may also be buried deep in library files. Most methods of a model class are public, however, some methods are private. They are called helper methods. 35

  36. 8.4 Constructors The code for a constructor in a model class initializes all of a newly instantiated object’s instance variables to some values. Default constructors have empty parameter lists. If you write a model class and don’t provide a default constructor, then Java will provide one for you automatically behind the scenes if someone tries to call it. In this case, Java will initialize the instance variables to whatever values it thinks are best. Initializing constructors have at least one parameter in their parameter lists. A class is easier to use when it has a variety of constructors. 36

  37. Remember the initializing constructor of the Person class. • public Person (String nm, int ag, int ad, int ph) • { • name = nm; • age = ag; • address = ad; • phone = ph; • } • Sometimes programmers don’t like to write abbreviations for the name of the parameters that initialize the instance variables. So it is possible to use the same names as the instance variables if you include the key word thiswhen referring to the instance variables. • public Person (String name, int age, int address, int phone) • { • this.name = name; • this.age = age; • this.address = address; • this.phone = phone; • } 8.4 Initializing Constructor of the Person Class Programmers are generally split on which way to do this, so there is no clear cut convention that is followed. 37

  38. 8.4 Using Chaining with Constructors Chaining is something that programmers sometimes use to write the code for model methods, but also classes that are not model classes. We will not utilize chaining in our coding exercises, however, we do want to show you an example of what chaining is. 38

  39. // Default Constructor • public Student3() • { • this("", 0, 0, 0); • } • // Initializing Constructor • public Student3 (String name, int test1, int test2, int test3) • { • this.name = name; • this.test1 = test1; • this.test2 = test2; • this.test3 = test3; • } • // Copy Constructor • public Student3 (Student3 s) • { • this (s.name, s.test1, s.test2, s.test3); • } • (Note: This is code from the Student3 class) 8.4 Chaining Constructors by Using this call the constructor of this class that has 4 parameters. Notice that the parameter names are the same as the instance variables so this must be used to distinguish between the instance variable and the parameter. instance variables parameters call the constructor of this class that has 4 parameters. 39

  40. 8.4 Calling Model Class Methods with This • In a model class, this can preface the name of any instance variable to access the data value in it or it can be used to call any method in the class as seen here: publicdouble getAverage ( ) { double average; int sum = this.sumTests(); average = (double) sum / 3; return average; } public String toString() { String str; str = ”\nName: " + this.name + "\n" + "Test 1: " + this.test1 + "\n" + "Test 2: " + this.test2 + "\n" + "Test 3: " + this.test3 + "\n" + "Average: " + this.getAverage() + "\n"; return str; } In these two methods, this is used to call other methods of the Student class. 40

  41. 8.4 Private Helper Methods • Occasionally, a task performed by a method becomes so complex that it helps to break it down into subtasks to be solved by one or more other methods. • Usually these additional methods are private because they do not need to be called by client programmers, but only by methods within the class where the helper method exists. 41

  42. 8.4 Private Helper Methods When a method is declared private, then it is meant to be called only from other methods in the same class, not other client classes! publicdouble getAverage ( ) { double average; int sum = this.sumTests();<-- call the private helper method average = (double) sum / 3; return average; } // PRIVATE HELPER METHOD ... CLIENT PROGRAMMERS CAN'T CALL THIS METHOD. This method isintended to only be called by other methods of this class!!! privateint sumTests( ) { int sum; sum = this.test1 + this.test2 + this.test3; return sum; } 42

  43. 8.4 Dividing Responsibility into Classes • As already stated, it is a good idea to divide the code for interactive applications into at least two sets of classes: • view classes • model classes • A view class handles the interactions with the user, such as input and output and major algorithms that manipulate objects of one or more model classes. An example of a view class is PersonDriver.java or StudentApp.java or AutoDriver.java. • A model class represents or models the kind of objects used or manipulated by a view class. Person.java,Student.java, and Auto.java are all model classes. 43

  44. 8.4 The Student Class Constructors • The Students class has 3 constructors with these method signatures: • public Student() • public Student (String nm, int t1, int t2, int t3) • public Student (Student s) • Note: all of these method signatures have no return types. But what kind of value is returned by each of these constructors??? 44

  45. 8.4 The Student Class Constructors • The Students class has 3 constructors with these method signatures: • public Student() • public Student (String nm, int t1, int t2, int t3) • public Student (Student s) • Note: all of these method signatures have no return types. But what kind of value is returned by each of these constructors??? A Student object! 45

  46. 8.4 Calling the Student Class Constructors To declare and instantiate a Student object, we would use one of the following lines in a driver (view) file, like StudentAp.java: • Student s1 = newStudent (); • Student s2 = newStudent (“Ann”, 92, 95, 88); • Student s3 = newStudent (s2); The last constructor is called a copy constructor and many programmers say you shouldn’t provide one. They say there should be no reason to make a copy. We show you an example of it so you know it can be done in Java. 46

  47. 8.4 Sending the getName message Send the message to the Student object s2 that you want its name. Since the method returns a string, store the returned value in a string variable in case you want to do something with it: String nm =s2.getName(); Note: to accomplish this we use an assignment statement!!! Note:we have to call the method with the object variable whose name we want to get. Since we want to get the name of the s2 object, we use s2 and the “dot” (method selector) before the name of the method. 47

  48. 8.4 Sending the setName message Send the message to the Student object s2 that you want to change its name. The method is a void method and doesn’t return a value. Therefore, we will NOT use an assignment statement.(Maybe s2 was instantiated with the wrong name so we need to call this mutator.) s2.setName(“Bill”); 48

  49. 8.4 Sending the toString message Send the message to the Student object s2 that you want to print all of its data. The method returns a String value. We can either use an assignment statement and store the returned value in a String variable or you can directly print the returned value in a println statement … String data= s2.toString(); System.out.println(data); OR just … System.out.println(s2.toString()); 49

  50. 8.4 Implicit & Explicit toString calls • Java lets you call the toString() method explicitly or implicitly. • Explicitly call the toString method for Student object s2 System.out.println(s2.toString()); • Implicitly call the toString method for Student object s2 System.out.println(s2); 50

More Related