Chapter 5 Introduction to Defining Classes Fundamentals of






























































- Slides: 62

Chapter 5 Introduction to Defining Classes Fundamentals of Java

Objectives l l l 2 Design and implement a simple class from user requirements. Organize a program in terms of a view class and a model class. Use visibility modifiers to make methods visible to clients and restrict access to data within a class. Fundamentals of Java

Objectives (cont. ) l l 3 Write appropriate mutator methods, accessor methods, and constructors for a class. Understand how parameters transmit data to methods. Use instance variables, local variables, and parameters appropriately. Organize a complex task in terms of helper methods. Fundamentals of Java

Vocabulary l l l 4 Accessor Actual parameter Behavior Constructor Encapsulation Fundamentals of Java

Vocabulary (cont. ) l l l 5 Formal parameter Helper method Identity Instantiation Lifetime Fundamentals of Java

Vocabulary (cont. ) l l 6 Mutator Scope State Visibility modifier Fundamentals of Java

Homework l l 7 Read 5. 1, 5. 2 Complete Exercises 5. 1, 5. 2 Fundamentals of Java

Classwork (DO NOW) l l - 8 If you haven’t already finished the Student class, go to bpi. edu and copy it into yours. Write the following functions for the Student class: get. Test. Average- has no parameters and returns the average of the 3 tests. get. Best. Test- has no parameters and returns the score of the highest test. Fundamentals of Java

Classwork (DO NOW) l l l 9 If you haven’t already finished the Student class, go to bpi. edu and copy it into yours. Add to the to. String method so that it also includes the students test average and best test. Create a Student. Test class. Create a new Student using the default contructor. Set the name to “Student, Test”, and the test scores to 71, 83, and 91 Verify that your class works by calling and displaying the to. String of this object Fundamentals of Java

The Internal Structure of Classes and Objects l A class is a template that describes the characteristics of similar objects. – Variable declarations define an object’s data. l Instance – 10 variables Methods define an object’s behavior in response to messages. Fundamentals of Java

The Internal Structure of Classes and Objects (cont. ) l l l 11 Encapsulation: Combining data and behavior into a single software package An object is an instance of its class. Instantiation: Process of creating a new object Fundamentals of Java

The Internal Structure of Classes and Objects (cont. ) l During execution, a computer’s memory holds: – – – l l Memory for data is allocated within objects. Objects appear and occupy memory when instantiated. – 12 All class templates in their compiled form Variables that refer to objects Objects as needed Disappear when no longer needed Fundamentals of Java

The Internal Structure of Classes and Objects (cont. ) l Garbage collection: JVM’s automated method for removing unused objects – l Three characteristics of an object: – – – 13 Tracks whether objects are referenced by any variables Behavior (methods) State (data values) Identity (unique ID for each object) Fundamentals of Java

The Internal Structure of Classes and Objects (cont. ) l When messages sent, two objects involved: – Client: The message sender l Only – needs to know the interface of the server Server: The message receiver l Supports l 14 and implements an interface Information hiding: Server’s data requirements and method implementation hidden from client Fundamentals of Java

A Student Class 15 Table 5 -1: Interface for the Student class Fundamentals of Java

A Student Class: Using Student Objects l Declare and instantiate a Student object: – l Sending messages to a Student object: – – – 16 Student s 1 = new Student(); String str = s 1. get. Name(); s 1. set. Name(“Bill”); System. out. println(s 1. to. String()); Fundamentals of Java

Homework l l 17 Read 5. 3, 5. 4 Complete Exercises 5. 3, 5. 4 Fundamentals of Java

A Student Class: Objects, Assignment, and Aliasing l Multiple variables can point at the same object – Example: l Student s 1 = new Student(); Student s 2 = s 1; l To cause a variable to no longer point at any object, set it equal to null, as in: – 18 s 1 = null; Fundamentals of Java

A Student Class: Objects, Assignment, and Aliasing (cont. ) 19 Table 5 -2: How variables are affected by assignment statements Fundamentals of Java

A Student Class: Objects, Assignment, and Aliasing (cont. ) 20 Table 5 -2: How variables are affected by assignment statements (cont. ) Fundamentals of Java

A Student Class (cont. ) l Two fundamental data type categories: – Primitive types: int, double, boolean, char l Shorter – and longer versions of these types Reference types: All classes Figure 5 -2: Difference between primitive and reference variables 21 Fundamentals of Java

A Student Class (cont. ) Figure 5 -3: Student variable before and after it has been assigned the value null 22 Fundamentals of Java

Homework l l 23 Read 5. 5, 5. 6 Complete Exercises 5. 5, 5. 6 Fundamentals of Java

A Student Class (cont. ) l Can compare a reference variable to null – 24 Avoid null pointer exceptions Fundamentals of Java

A Student Class: The Structure of a Class Template 25 Fundamentals of Java

A Student Class: The Structure of a Class Template (cont. ) l public: Class is accessible to anyone l Name of class must follow Java naming conventions extends: Optional l – – 26 Java organizes class in a hierarchy. If Class B extends Class A, it inherits instance variables and methods from Class A. Fundamentals of Java

A Student Class: The Structure of a Class Template (cont. ) Figure 5. 4: Relationship between superclass and subclass 27 Fundamentals of Java

A Student Class: The Structure of a Class Template (cont. ) l private and public are visibility modifiers. – Define whether a method or instance variable can be seen outside of the class l Instance 28 variables should generally be private. Fundamentals of Java

A Student Class: Constructors (cont. ) l Initialize a newly instantiated object’s instance variables – l l 29 Activated (called) only by the keyword new Default constructors: Empty parameter lists A class is easier to use when it has a variety of constructors. Fundamentals of Java

A Student Class: Chaining Constructors (cont. ) 30 Fundamentals of Java

Editing, Compiling, and Testing the Student Class l Steps: – Save source code in Student. java. Run javac Student. java. – Run/test the program. – 31 Fundamentals of Java

Editing, Compiling, and Testing the Student Class (cont. ) Example 5. 1: Tester program for the Student class 32 Fundamentals of Java

Editing, Compiling, and Testing the Student Class (cont. ) l 33 Introduce an error into the Student class: Figure 5 -6: Divide by zero run-time error message Fundamentals of Java

The Structure and Behavior of Methods 34 l Methods take the following form: l If the method returns no value, the return type should be void. Fundamentals of Java

Homework l 35 Ch 5 Written Questions Fundamentals of Java

The Structure and Behavior of Methods (cont. ) l return statements: If a method has a return type, implementation must have at least one return statement that returns a value of that type. – – 36 A return statement in a void method simply ends the method. Can have multiple return statements Fundamentals of Java

The Structure and Behavior of Methods (cont. ) l l l 37 Formal parameters: Parameters listed in a method’s definition Actual parameters (arguments): Values passed to a method when it is invoked Parameter passing example: Fundamentals of Java

The Structure and Behavior of Methods (cont. ) Figure 5. 8: Parameter passing 38 Fundamentals of Java

The Structure and Behavior of Methods (cont. ) l Helper methods: Perform a piece of a task – – Used by another method to perform a larger task Usually private l Only methods already defined within the class need to use them l 39 When an object is instantiated, it receives own copy of its class’s instance variables Fundamentals of Java

Scope and Lifetime of Variables l Global variables: Declared inside a class but outside any method – l Local variables: Declared inside a method – 40 Accessible to any method in the class Accessible only within that method Fundamentals of Java

Scope and Lifetime of Variables (cont. ) l l Scope (of a variable): Region where a variable can validly appear in lines of code Variables declared within any compound statement enclosed in braces have block scope. – 41 Visible only within code enclosed by braces Fundamentals of Java

Scope and Lifetime of Variables (cont. ) l Lifetime: Period when a variable can be used – – l Local variables exist while the method executes. Instance variables exist while the object exists. Duplicate variable names may exist. – – Local variables in different scopes A local and a global variable Local overrides global l Use this keyword to access global variable. l 42 Fundamentals of Java

Scope and Lifetime of Variables (cont. ) 43 Fundamentals of Java

Scope and Lifetime of Variables (cont. ) l Use instance variables to retain data. – l Use local variables for temporary storage. – l 44 Using local variables will result in lost data. Using global variables could cause difficult-toresolve logic errors. Use method parameters rather than global variables whenever possible. Fundamentals of Java

Graphics and GUIs: Images l To load an image: – Image. Icon image = new Image. Icon(file. Name); l l To paint an Image. Icon from a panel class: – – – 45 file. Name indicates the location and name of a file containing an image. an. Image. Icon. paint. Icon(this, g, x, y); g is the graphics context. x and y are panel coordinates. Fundamentals of Java

Graphics and GUIs: A Circle Class l Useful to represent shapes as objects – – 46 A shape has attributes (color, size, position). Can create more shapes than the Graphics class can draw Given its graphics context, a shape can draw itself. Easier to manipulate Fundamentals of Java

Graphics and GUIs: A Circle Class (cont. ) 47 Table 5 -4: Methods in class Circle Fundamentals of Java

Graphics and GUIs: A Circle Class (cont. ) Table 5 -4: Methods in class Circle (cont. ) 48 Fundamentals of Java

Graphics and GUIs: A Circle Class (cont. ) 49 Example 5. 3: Displays a circle and a filled circle Fundamentals of Java

Graphics and GUIs: A Circle Class (cont. ) Figure 5 -10: Displaying two Circle objects 50 Fundamentals of Java

Graphics and GUIs: A Circle Class (cont. ) l repaint method: Forces a refresh of any GUI component – Invokes object’s paint. Component method – Called automatically by the JVM whenever the component is moved or altered Can programatically call repaint() as well – 51 Fundamentals of Java

Graphics and GUIs: Mouse Events l Program can detect and respond to mouse events by attaching listener objects to a panel – – – 52 When a particular type of mouse event occurs in a panel, its listeners are informed. Listener class for capturing mouse click events extends Mouse. Adapter Listener class for capturing mouse motion and dragging events extends Mouse. Motion. Adapter Fundamentals of Java

Graphics and GUIs: Mouse Events (cont. ) Table 5 -5: Methods for responding to mouse events 53 Fundamentals of Java

Graphics and GUIs: Mouse Events (cont. ) Example 5. 5: Displays a circle and a filled circle. Allows the user to drag a circle to another position 54 Fundamentals of Java

Graphics and GUIs: Mouse Events (cont. ) 55 Example 5. 5: Displays a circle and a filled circle. Allows the user to drag a circle to another position (cont. ) Fundamentals of Java

Graphics and GUIs: Mouse Events (cont. ) 56 Example 5. 5: Displays a circle and a filled circle. Allows the user to drag a circle to another position (cont. ) Fundamentals of Java

Graphics and GUIs: Mouse Events (cont. ) 57 Example 5. 5: Displays a circle and a filled circle. Allows the user to drag a circle to another position (cont. ) Fundamentals of Java

Summary l l 58 Java class definitions consist of instance variables, constructors, and methods. Constructors initialize an object’s instance variables when the object is created. A default constructor expects no parameters and sets the variables to default values. Mutator methods modify an object’s instance variables. Fundamentals of Java

Summary (cont. ) l l Accessor methods allow clients to observe the values of these variables. The visibility modifier public makes methods visible to clients. private encapsulates access. Helper methods are called from other methods in a class definition. – 59 Usually declared to be private Fundamentals of Java

Summary (cont. ) l l 60 Instance variables track the state of an object. Local variables are used for temporary working storage within a method. Parameters transmit data to a method. A formal parameter appears in a method’s signature and is referenced in its code. Fundamentals of Java

Summary (cont. ) l l l 61 Actual parameter is a value passed to a method when it is called. Scope of an instance variable is the entire class within which it is declared. Scope of a local variable or a parameter is the body of the method where it is declared. Fundamentals of Java

Summary (cont. ) l l 62 Lifetime of an instance variable is the same as the lifetime of a particular object. Lifetime of a local variable and a parameter is the time during which a particular call of a method is active. Fundamentals of Java