Chapter 6 Introduction to Defining Classes

Slides:



Advertisements
Similar presentations
Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view class.
Advertisements

Chapter 8 Improving the User Interface
L3:CSC © Dr. Basheer M. Nasef Lecture #3 By Dr. Basheer M. Nasef.
Chapter 3 Introduction to Classes, Objects, Methods, and Strings
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 3 Syntax, Errors, and Debugging
Chapter 10 Introduction to Arrays
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Chapter 11 Classes Continued
Road Map Introduction to object oriented programming. Classes
 2006 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
VBA Modules, Functions, Variables, and Constants
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
ASP.NET Programming with C# and SQL Server First Edition
Chapter 10 Classes Continued
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Chapter 10 Introduction to Classes
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
JAVA Classes Review. Definitions Class – a description of the attributes and behavior of a set of computational objects Constructor – a method that is.
1 Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 26 - Java Object-Based Programming Outline 26.1Introduction.
CS451 - Lecture 2 1 CS451 Lecture 2: Introduction to Object Orientation Yugi Lee STB #555 (816) * Acknowledgement:
Classes. Constructor A constructor is a special method whose purpose is to construct and initialize objects. Constructor name must be the same as the.
Chapter 5 Introduction to Defining Classes
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Objects and Classes.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 6 Objects and Classes.
 2008 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Creating a Java Application and Applet
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Creating Java Applications (Software Development Life Cycle) 1. specify the problem requirements - clarify 2. analyze the problem - Input? Processes? Output.
1 Guide gus; Creates a “mailbox” to hold the address of a Guide object. null gus.
1 Sections 6.4 – 6.5 Methods and Variables Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Sections Inheritance and Abstract Classes
3 Introduction to Classes and Objects.
Introduction to Classes and Objects
Java Programming: Guided Learning with Early Objects
Java Primer 1: Types, Classes and Operators
Intro To Classes Review
Chapter 3: Using Methods, Classes, and Objects
Section 11.1 Class Variables and Methods
Can perform actions and provide communication
Chapter 3 Introduction to Classes, Objects Methods and Strings
Can perform actions and provide communication
Defining Classes and Methods
Lesson 5: Introduction to Defining Classes
Can perform actions and provide communication
Defining Classes and Methods
Object Oriented Programming in java
Classes, Objects and Methods
Chapter 7 Objects and Classes
Presentation transcript:

Chapter 6 Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition Lambert / Osborne

Objectives 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. 2 2

Objectives (continued) 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. 3 3

Vocabulary accessor actual parameter behavior constructor encapsulation formal parameter helper method identity Instantiation lifetime mutator scope state visibility modifier 4 4

The Internal Structure of Classes and Objects An object is a runtime entity that contains data and responds to messages. A class is a software package or template that describes the characteristics of similar objects. Instance variable declarations which define an object’s data requirements. Methods that define its behavior in response to messages. 5 5

The Internal Structure of Classes and Objects (continued) Encapsulation: the combining of data and behavior into a single software package. Instantiation: The process of creating a new object. 6 6

The Internal Structure of Classes and Objects (continued) Classes, Objects, and Computer Memory: When a Java program is executing, the computer’s memory must hold: All class templates in their compiled form. Variables that refer to objects. Objects as needed. Each method’s compiled byte code is stored in memory as part of its class’s template. 7 7

The Internal Structure of Classes and Objects (continued) Classes, Objects, and Computer Memory (cont): Memory for data is allocated within objects. Although all class templates are in memory at all times, individual objects come and go. An object occupies memory with it is instantiated, and disappears when no longer needed. Garbage collection: the JVM process of keeping track of which objects need to be stored and which can be deleted. 8 8

The Internal Structure of Classes and Objects (continued) Three Characteristics of an Object: Behavior: defined by the methods of its class. State: at any moment the instance variables have particular values, which change in response to messages sent to the object. Identity: distinguish from other objects in memory, as handled by the JVM. 9 9

The Internal Structure of Classes and Objects (continued) Three Characteristics of an Object (cont): Of the variables, there can be none, one, or several. When there are none, the garbage collector purges the object from memory. Clients, Servers, and Interfaces: Clients send messages. Only need to know the server’s interface. Information hiding hides the server’s data requirements and list of supported methods from clients. 10

A Student Class Using Student Objects: First, declare variables, then assign values to variables before using them. Mutators: messages that change an object’s state. Accessors: messages that access the object’s state. Used to see if a mutator works correctly. 11 11

A Student Class (continued) Implicit use of toString when a Student object is sent to a terminal window 12 12

A Student Class (continued) Objects, Assignment, and Aliasing: An object can be assigned two variables. At any time, it is possible to break the connection to a variable and the object it references by assigning the null value to the variable. 13 13

A Student Class (continued) How variables are affected by assignment statements 14

A Student Class (continued) Primitive Types, Reference Types, and the null Value: In Java, all types fall into two categories: Primitive: 1 box that contains a value of primitive type. int, double, boolean, char, and longer and shorter versions of these. Reference: a box that contains a pointer to an object. String, Student, Scanner, and all classes. 15 15

A Student Class (continued) Primitive Types, Reference Types, and the null Value (cont): The difference between primitive and reference variables 16 16

A Student Class (continued) Primitive Types, Reference Types, and the null Value (cont): Can assign reference variables the null value. If it pointed to an object, and no other variable points to the object, the object’s memory goes to garbage collection. The Student variable before and after it has been assigned the value null 17 17

A Student Class (continued) Primitive Types, Reference Types, and the null Value (cont): Null pointer exception: when a program attempts to run a method with a null object. 18 18

A Student Class (continued) The Structure of a Class Template: All classes have a similar structure consisting of 4 parts: The class’s name and some modifying phrases. A description of the instance variables. One or more constructor method that indicates how to initialize a new object. One or more methods that specify how an object responds to messages. 19

A Student Class (continued) The Structure of a Class Template (cont): Class definitions: usually begin with the keyword public. Class names: user-defined symbols that adhere to rules for naming variables and methods. Java organizes classes in a hierarchy. Base: Object. Superclasses and subclasses. Each class, except Object, can have one parent and any number of children. 20 20

A Student Class (continued) The Structure of a Class Template (cont): Inheritance: a new class inherits the characteristics of its superclass. Extends the superclass by modifying and adding. Instance variables are nearly always private. Visibility modifiers: private and public. Determine whether clients can see them. 21 21

A Student Class (continued) The Structure of a Class Template (cont): When an object receives a message, it activates the corresponding method, which manipulates the object’s data as represented by the instance variables. Constructors: Purpose of a constructor is the initialize the instance variables of a newly instantiated object. 22 22

A Student Class (continued) Constructors (cont): Constructors are only ever activated when the keyword new is used. A class template can have more than one constructor, as long as each has a unique parameter list. All constructors must have the same name as the class. Default constructors have empty parameter lists. 23 23

A Student Class (continued) Constructors (cont): A class is easier to use when it has a variety of constructors. Chaining Constructors: Used when a class has several constructors. Simplifies code by calling one constructor from another: This(<parameters>); 24 24

Editing, Compiling, and Testing the Student Class To use the Student class, save it in a file called Student.java and compile it. Once the Student class is compiled, applications can declare and manipulate Student objects if one of the following is true: The code for the application and class are in the same directory. The class is part of a package. 25 25

Editing, Compiling, and Testing the Student Class (continued) Output from the TestStudent program 26 26

Editing, Compiling, and Testing the Student Class (continued) Finding the Location of Run-Time Errors: The messages list the line and help trace the errors in order to fix them. Divide by zero run-time error message 27 27

The Structure and Behavior of Methods A method is a description of a task that is performed in response to a message. The Structure of a Method Definition: Use the visibility modifiers public and private to determine if the method is available to clients of the defining class. 28 28

The Structure and Behavior of Methods (continued) The Structure of a Method Definition (cont): The return type should be void when the method returns no value. Method names have the same syntax as other Java identifiers. Parentheses are required whether or not parameters are present. A parameter list, consists of one or more pairs of type names and parameter names, separated by commas. 29 29

The Structure and Behavior of Methods (continued) The Structure of a Method Definition (cont): Stub: a method whose implementing code is omitted. Stubs are used to set up incomplete but running programs during program development. Return Statements: If a method has a return type, its implementing code must have at least one return statement that returns a value of that type. 30 30

The Structure and Behavior of Methods (continued) Formal and Actual Parameters: Formal parameters are listed in a method’s definition. Actual parameters, or arguments, are values passed to a method when it is invoked. When a method has multiple parameters, the caller must provide the right number and types of values. 31 31

The Structure and Behavior of Methods (continued) Parameters and Instance Variables: The purpose of a parameter is to pass information to a method. The purpose of an instance variable is to maintain information in an object. Local Variables: Used to provide temporary working storage for data in a method. 32 32

The Structure and Behavior of Methods (continued) Helper Methods: Breaks a complex task performed by a method into subtasks. Usually private, because only the methods in the class need to use them. 33 33

Scope and Lifetime of Variables Scope of Variables: The scope of a variable is that region of the program within which the variable can validly appear in lines of code. A local variable is restricted to the body of the method that declares it. A private instance variable’s scope is the methods in its defining class. 34 34

Scope and Lifetime of Variables (continued) Scope of Variables (cont): Variables and their scope 35

Scope and Lifetime of Variables (continued) Block Scope: Variables declared within (nested) any compound statement enclosed in braces. Lifetime of Variables: The period during which it can be used. Local variables and formal parameters exist during a single execution of a method. Instance variables last for the lifetime of the object. 36 36

Scope and Lifetime of Variables (continued) Duplicating Variable Names: The same name can be used for different methods because the scope of a formal parameter or local variable is restricted to a single method. A local variable with the same name as an instance variable is said to shadow it. 37 37

Scope and Lifetime of Variables (continued) When to Use Instance Variables, Parameters, and Local Variables: Instance variable: to store information within an object. Parameter: to transmit information to a method. Local variable: temporary working storage within a method. 38 38

Scope and Lifetime of Variables (continued) When to Use Instance Variables, Parameters, and Local Variables (cont): Common mistakes: Instance variable used for temporary working storage. Local variable used to remember information as an object. Method accesses data by directly referencing an instance variable instead of using a parameter. 39 39

Scope and Lifetime of Variables (continued) When to Use Instance Variables, Parameters, and Local Variables (cont): Reasons to prefer the use of parameters: If several methods share a pool of variables and one method misuses a variable, the other methods are affected. It is easier to understand methods and their relationships when defined by parameters and return values. Methods that are passed parameters can be reused in different situations. 40 40

Graphics and GUIs: Images, a Circle Class, and Mouse Events Loading Images from Files and Displaying Them: Some image file formats: JPEG, GIF, or PNG. Once an image is available, a Java application can load it into RAM for use. ImageIcon image = new ImageIcon(filename); Creates an ImageIcon object with a bitmap for the data in the image. 41 41

Graphics and GUIs: Images, a Circle Class, and Mouse Events (continued) Loading Images from Files and Displaying Them (cont): Example: program has a main application class that loads an image of a cat and passes the image to a new ColorPanel. The ColorPanel receives the image icon at instantiation and saves a reference in an instance variable. The ColorPanel maintains another object, an image, as part of its state. 42 42

Graphics and GUIs: Images, a Circle Class, and Mouse Events (continued) Geometric Shapes: It is useful to implement each shape as a distinct object with its own methods: Allows users to manipulate attributes (color, size, etc.). Allows more specific and complex shapes. If a shape knows its own attributes, it just needs a graphic context in order to display. Easy for programs that use multiple shapes and designs. 43 43

Graphics and GUIs: Images, a Circle Class, and Mouse Events (continued) Defining a Circle Class: Circles have a color, center point, and radius. Users can ask a circle to draw or fill itself, or if a circle contains a given point (x,y). Implementation of the Circle Class: The constructor receives the color, center point, and radius and assigns these values to instance variables. 44 44

Graphics and GUIs: Images, a Circle Class, and Mouse Events (continued) Using the Circle Class: Displaying two Circle objects 45 45

Graphics and GUIs: Images, a Circle Class, and Mouse Events (continued) The Method repaint: Used to refresh a GUI component, such as a panel. Example: move a shape to a new coordinate in response to a mouse click. Responses to Mouse Events: Button presses and releases, mouse movement, dragging, and mouse entry/exit. 46 46

Graphics and GUIs: Images, a Circle Class, and Mouse Events (continued) Responses to Mouse Events (cont): Listener objects: attached to a panel, and used to detect and respond to mouse events. If a listener has a method whose parameter matches the type of mouse event, the JVM runs the method and passes the event object to it as a parameter. The event object contains the mouse’s panel coordinates. 47 47

Graphics and GUIs: Images, a Circle Class, and Mouse Events (continued) Dragging Circles: Example: the user selects a circle by pressing the mouse, and moves it by dragging. Uses three types of events and responses: Mouse press: saves the coordinates of the mouse. Mouse release: deselects the shape and sets the saved reference to null. Mouse drag: computes the x and y distances between the current and saved mouse coordinates. 48 48

Summary In this chapter, you learned: 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 reasonable default values. Other constructors expect parameters that allow clients to set up objects with specified data. 49 49

Summary (continued) Mutator methods modify an object’s instance variables, whereas accessor methods merely allow clients to observe the values of these variables. The visibility modifier public is used to make methods visible to clients, whereas the visibility modifier private is used to encapsulate or restrict access to variables and methods. Helper methods are methods that are called from other methods in a class definition. They are usually declared to be private. 50 50

Summary (continued) Variables within a class definition can be instance variables, local variables, or parameters. Instance variables are used to track the state of an object. Local variables are used for temporary working storage within a method. Parameters are used to transmit data to a method. A formal parameter appears in a method’s signature and is referenced in its code. An actual parameter is a value passed to a method when it is called. A method’s actual parameters must match its formal parameters in number, position, and type. 51 51

Summary (continued) The scope of a variable is the area of program text within which it is visible. The scope of an instance variable is the entire class within which it is declared. The scope of a local variable or a parameter is the body of the method within which it is declared. The lifetime of a variable is the period of program execution during which its storage can be accessed. The lifetime of an instance variable is the same as the lifetime of a particular object. The lifetime of a local variable and a parameter is the time during which a particular call of a method is active. 52 52