Chapter 6 Introduction to Defining Classes

Similar documents
Introduction to Programming Using Java (98-388)

Chapter 4 Defining Classes I

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Java Object Oriented Design. CSC207 Fall 2014

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

Java Primer 1: Types, Classes and Operators

CHAPTER 7 OBJECTS AND CLASSES

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

CHAPTER 7 OBJECTS AND CLASSES

CMSC 132: Object-Oriented Programming II

EECS168 Exam 3 Review

Chapter 10 Classes Continued. Fundamentals of Java

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

CS-202 Introduction to Object Oriented Programming

Computer Science II (20073) Week 1: Review and Inheritance

Objects and Classes. 1 Creating Classes and Objects. CSCI-UA 101 Objects and Classes

Subclass Gist Example: Chess Super Keyword Shadowing Overriding Why? L10 - Polymorphism and Abstract Classes The Four Principles of Object Oriented


Inheritance, Polymorphism, and Interfaces

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Programming II (CS300)

CS 251 Intermediate Programming Methods and Classes

Short Notes of CS201

Data Structures (list, dictionary, tuples, sets, strings)

CS201 - Introduction to Programming Glossary By

CMSC 132: Object-Oriented Programming II

C++ Important Questions with Answers

CS1004: Intro to CS in Java, Spring 2005

Cpt S 122 Data Structures. Introduction to C++ Part II

CS 251 Intermediate Programming Methods and More

Programming II (CS300)

Defining Classes and Methods

Programming overview

Fundamental Concepts and Definitions

CLASSES AND OBJECTS IN JAVA

What are the characteristics of Object Oriented programming language?

CS260 Intro to Java & Android 03.Java Language Basics

Java: introduction to object-oriented features

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Paytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value

Chapter 1: Object-Oriented Programming Using C++

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

1 Shyam sir JAVA Notes

What about Object-Oriented Languages?

Programming II (CS300)

7. C++ Class and Object

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

8. Polymorphism and Inheritance

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Chapter 5: Procedural abstraction. Function procedures. Function procedures. Proper procedures and function procedures

COP 3330 Final Exam Review

12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.

Chapter 14 Abstract Classes and Interfaces

Chapter 4 Java Language Fundamentals

OBJECT ORİENTATİON ENCAPSULATİON

Glossary. For Introduction to Programming Using Python By Y. Daniel Liang

Inheritance CSC 123 Fall 2018 Howard Rosenthal

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Comments are almost like C++

Object-Oriented Programming Concepts

Defining Classes and Methods

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

The Decaf Language. 1 Lexical considerations

Curriculum Map Grade(s): Subject: AP Computer Science

Methods and Data (Savitch, Chapter 5)

STRUCTURING OF PROGRAM

Object-Oriented Programming

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Chapter 7. Inheritance

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107


OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

COMP 250 Winter 2011 Reading: Java background January 5, 2011

CS 231 Data Structures and Algorithms, Fall 2016

Objects and Classes Lecture 2

Inheritance and Polymorphism

OO Programming Concepts. Classes. Objects. Chapter 8 User-Defined Classes and ADTs

More About Objects and Methods

Methods. Methods. Mysteries Revealed

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

What is Inheritance?

Instance Members and Static Members

CS304 Object Oriented Programming Final Term

JAVA GUI PROGRAMMING REVISION TOUR III

CH. 2 OBJECT-ORIENTED PROGRAMMING

Chapter 4. Defining Classes I

CSE 307: Principles of Programming Languages

Object Oriented Modeling

2. The object-oriented paradigm

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Data Abstraction. Hwansoo Han

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Object Oriented Programming. Solved MCQs - Part 2

Chapter 4. Defining Classes I

2. The object-oriented paradigm!

Classes. Logical method to organise data and functions in a same structure. Also known as abstract data type (ADT).

Objects and Classes. Basic OO Principles. Classes in Java. Mark Allen Weiss Copyright 2000

Object Class. EX: LightSwitch Class. Basic Class Concepts: Parts. CS257 Computer Science II Kevin Sahr, PhD. Lecture 5: Writing Object Classes

Transcription:

Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1

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

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

Vocabulary accessor actual parameter behavior constructor encapsulation formal parameter helper method identity Instantiation lifetime mutator scope state visibility modifier 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

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

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

The Internal Structure of Classes and Objects (continued) 8 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.

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

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

A Student Class (continued) Implicit use of tostring when a Student object is sent to a terminal window 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

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

A Student Class (continued) Primitive Types, Reference Types, and the null Value (cont): The difference between primitive and reference variables 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

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

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) 20 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.

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

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

A Student Class (continued) 23 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.

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

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

Editing, Compiling, and Testing the Student Class (continued) Output from the TestStudent program 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

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

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

The Structure and Behavior of Methods (continued) 30 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.

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

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

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

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

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

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

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

Scope and Lifetime of Variables (continued) 39 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.

Scope and Lifetime of Variables (continued) 40 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.

Graphics and GUIs: Images, a Circle Class, and Mouse Events 41 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.

Graphics and GUIs: Images, a Circle Class, and Mouse Events (continued) 42 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.

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

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

Graphics and GUIs: Images, a Circle Class, and Mouse Events (continued) Using the Circle Class: Displaying two Circle objects 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

Graphics and GUIs: Images, a Circle Class, and Mouse Events (continued) 47 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.

Graphics and GUIs: Images, a Circle Class, and Mouse Events (continued) 48 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.

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

Summary (continued) 50 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.

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

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