CHAPTER 7 OBJECTS AND CLASSES

Similar documents
CHAPTER 7 OBJECTS AND CLASSES

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

Chapter 6 Introduction to Defining Classes

Introduction to Programming Using Java (98-388)

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

CS 231 Data Structures and Algorithms, Fall 2016

Full file at

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.

Defining Classes and Methods

Java Primer 1: Types, Classes and Operators

CMPT 125: Lecture 3 Data and Expressions

CS260 Intro to Java & Android 03.Java Language Basics

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Program Fundamentals

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal

Values and Variables 1 / 30

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

VARIABLES AND TYPES CITS1001

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

Chapter 4 Defining Classes I

Section 2: Introduction to Java. Historical note

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

CSE 142 Su 04 Computer Programming 1 - Java. Objects

Visual C# Instructor s Manual Table of Contents

Getting started with Java

Programming II (CS300)

Full file at

3.1 Class Declaration

STUDENT LESSON A5 Designing and Using Classes

Chapter 4. Defining Classes I

Chapter 2: Using Data

Pace University. Fundamental Concepts of CS121 1

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

CS-140 Fall 2017 Test 1 Version Practice Practie for Sept. 27, Name:

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

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

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Connecting with Computer Science, 2e. Chapter 15 Programming II

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Chapter 2: Basic Elements of C++

9 Working with the Java Class Library

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

CS 251 Intermediate Programming Methods and Classes

Short Notes of CS201

CS 251 Intermediate Programming Methods and More

Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A

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

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

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

13 th Windsor Regional Secondary School Computer Programming Competition

Chapter 2: Using Data

CS201 - Introduction to Programming Glossary By

public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Review Chapter 6 in Bravaco. Short Answers 1. This type of method does not return a value. a. null b. void c. empty d. anonymous

BM214E Object Oriented Programming Lecture 8

Programming with Java

Java Classes & Primitive Types

Java Classes & Primitive Types

Object-Oriented Programming Concepts

Lecture 2. COMP1406/1006 (the Java course) Fall M. Jason Hinek Carleton University

Simple Java Reference

Computational Expression

Decaf Language Reference Manual

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

Fundamental Concepts and Definitions

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

Introduction to Java

Lecture 2 Tao Wang 1

Ticket Machine Project(s)

3. Java - Language Constructs I

Object-Oriented Programming in C# (VS 2015)

CS162: Introduction to Computer Science II. Primitive Types. Primitive types. Operations on primitive types. Limitations

Java+- Language Reference Manual

Object Oriented Programming

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

Formatted Output Pearson Education, Inc. All rights reserved.

Java Basic Datatypees

CS112 Lecture: Variables, Expressions, Computation, Constants, Numeric Input-Output

Object Reference and Memory Allocation. Questions:

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Introduction to Classes and Objects Pearson Education, Inc. All rights reserved.

Chapter 02: Using Data

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Computer Programming : C++

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

C# Programming for Developers Course Labs Contents

Chapter 4: Writing Classes

Chapter 1: Object-Oriented Programming Using C++

MODULE 02: BASIC COMPUTATION IN JAVA

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

JavaScript: Sort of a Big Deal,

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

PROGRAMMING FUNDAMENTALS

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Chapter 1 GETTING STARTED. SYS-ED/ Computer Education Techniques, Inc.

1 Shyam sir JAVA Notes

Transcription:

CHAPTER 7 OBJECTS AND CLASSES

OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and classes. Describe how Java classes support encapsulation through member data and methods. Use the public and private access specifiers in Java programs. Explain the use of the new operator to instantiate objects from classes. Describe the use of references in Java and explain the role of garbage collection. Use constructors to initialize your objects. 2

Structured Data Java defines primitive data types that are built into the language. Data types such as int, double, and boolean can be used to represent simple data. Java provides the class mechanism to represent more complex forms of data. Through a class you can build up structured data out of simpler elements. public class Product { String description; double price; Product is now a new data type. A product has a description (e.g. Airplane toy ) and a price (e.g. 2.55). The Java libraries predefine many classes that you can use in your programs. String, although not a primitive data type, is predefined for you in the standard Java library. 3

Classes and Objects A class represents a kind of or type of data. It is analogous to the built-in types like int and double. A class can be thought of as a template from which individual instances can be created. When you create a class, you are only creating a definition. An instance of a class is called an object. Just as you can have several individual integers that are instances of int, you can have several products that are instances of Product. 4

References There is a fundamental distinction between the primitive data types and the extended data types that can be created using classes. When you declare a variable of a primitive data you are allocating memory and creating the instance. int x; // 4 bytes of memory have been allocated When you declare a variable of a class type (an object variable ), you are only obtaining memory for a reference to an object of the class type. No memory is allocated for the object itself, which may be quite large. Product p; // p is a reference to a Product object // The object itself does not yet exist 5

Instantiating and Using an Object You instantiate an object with the new operator. p = new Product (); // a Product object now exists // and p is a reference to it Once an object exists you work with it, including accessing its data members (or fields ) and methods. Our simple Product example at this point has no methods, only two data members. You access data members and methods using a dot (normally you will not access data members directly they are usually private ). p.description = "Airplane toy"; p.price = 2.55; // values have now been assigned p "Airplane toy" 2.55 Before the object exists, its object reference is null. You can test for an object reference being null. if (p!= null) { // OK to assign values p.description = "Airplane toy"; p.price = 2.55; 6

Assigning Object Variables Consider a second object variable referencing a second object. Product q = new Product(); q.description = Beanie baby ; q.price = 15.66 q "Beanie baby" 15.66 When you assign an object variable you are only assigning the reference, there is no copying of data. q = p; // q now refers to same object p does q "Beanie baby" 15.66 p "Airplane toy" 2.55 7

Garbage Collection Through the assignment of a reference, an object may become orphaned. Such an orphan object (or garbage ) takes up memory in the computer which can now never be referenced. Beanie baby is now garbage. q "Beanie baby" 15.66 p "Airplane toy" 2.55 The Java Virtual Machine automatically reclaims the memory of unreferenced objects. This process is known as garbage collection. Garbage collection takes up some execution time, but it is a great convenience for programmers, helping to avoid a common program error known as a memory leak. 8

Programming a Class EXAMPLE To program a class in Java do the following: Enter the class definition in a file. The file should have the same name as the class with the extension.java. Make the class public in order to be able to use it in other classes. Declare fields, which are like variables but they exist for the life of each object of the class, rather than just for the duration of a method invocation. Example program shows definition and use of a simple Product class. See Product_Step0. public class Product { String description; double price; 9

Default Values Notice that you do not need to initialize fields, though you can if you so choose. If you don t, the compiler will assign a default value, which is essentially the zero representation appropriate to the data type of the field. The following table shows the default value for the primitive data types: Type Default boolean false char \u0000 byte 0 short 0 int 0 long 0L float 0.0f double 0.0 Object references default to null. 10

Using a Class EXAMPLE To use a class: Declare a reference to the class and instantiate an object instance by new (can be done on the same line). Access members (and methods) by using the dot notation. See Product_Step0. public class TestProduct { public static void main(string[] args) { Product p1 = new Product(); Product p2 = new Product(); Product q; p1.description = "Airplane toy"; p1.price = 2.50; p2.description = "Beanie baby"; p2.price = 15.66; q = p1; System.out.println(q.description + " " + q.price); q = p2; System.out.println(q.description + " " + q.price); 11

Methods Typically a class will specify behavior as well as data. A class encapsulates data and behavior in a single entity. A method consists of: An access specifier, typically public or private. A return type (can be void if the method does not return data). A method name, which can be any legal Java identifier. A parameter list, enclosed by parentheses, which specifies data that is passed to the method (can be empty, if no data is passed). A method body, enclosed by curly braces, which contains the Java code that the method will execute. 12

Methods Example: The return type is void (no data is passed back). The method name is adjustprice. The parameter list consists of a single parameter of type double. The body contains one line of code that increments the member variable price by the value that is passed in. public void adjustprice(double p) { price += p; Example: The return type is double (data of type double will be passed back). The method name is getprice. There are no parameters. The body contains one line of code that returns the current value of member variable price. public double getprice() { return price; 13

Public and Private Data members and methods of a Java class can be specified as public or private. Normally you declare data members as private. A private member can only be accessed from within the class, not from outside. Methods may be declared as either public or private. Public methods are called from outside the class and are used to perform calculations and to manipulate the private data. You may also have private methods, which can be thought of as helper functions for use within the class (rather than duplicating code several places, you may create a private method, which will be called wherever it is needed). 14

Abstraction Our Product class captures the essential features of a product, suppressing unnecessary details. There are many possible features of a product, but for our purposes the only essential things are its description and its price. All instances of the Product class share these common features. This helps us deal with complexity. 15

Encapsulation Encapsulation is an important feature of Object Orientation. The implementation of a class should be hidden from the rest of the system, or encapsulated. Objects have a public and a private side. Public side is what the rest of the system knows, while private side implements the public side. Product p adjustprice price description Data itself should be private and only accessible through methods with a public interface. There are two kinds of protection: Internal data is protected from corruption. Users of the object are protected from changes in the representation. 16

Constructors Another important issue for classes is initialization. When an object is created, what initial values are assigned to the instance data? Through a constructor you can initialize an object in any way you wish. Besides initializing instance data you can perform other appropriate initializations (e.g. open a file). A constructor is like a special method which is automatically called when an object is created. A constructor has no return type. A constructor has the same name as the class. A constructor may take parameters, which are passed when invoking new. public Product(String d, double p) { description = d; price = p; 17

A Product Class EXAMPLE Another version of the Product class illustrates the features we have been discussing. See Product_Step1. public class Product { // constructor public Product(String d, double p) { description = d; price = p; public void adjustprice(double p) { // method increments the price by p price += p; public double getprice() { // method retrieves the price return price; public String getdescription() { // method retrieves the description return description; public String tostring() { // method converts to string return String.format("%s $%,1.2f", description, price); private String description; private double price; 18

A Product Class EXAMPLE public class TestProduct { public static void main(string[] args) { Product p1, p2, p3; p1 = new Product("Airplane toy", 2.50); // uses constructor p1.adjustprice(.50); // uses method p2 = new Product("Beanie baby", 15.66); p3 = new Product("Cat carrier", 5.50); // uses constructor System.out.println(p1.toString()); System.out.println(p2.toString()); System.out.println(p3.toString()); // conversion to string System.out.println(p3); // implicit conversion Try it out: compile run TestProduct Airplane toy $3.00 Beanie baby $15.66 Cat carrier $5.50 Cat carrier $5.50 19

The tostring Method It is often useful to define a tostring method in your class. This method should return a String value that represents the current object instance. tostring is known to Java. If an object reference is used when a String reference is expected, your object will be converted to a String using the tostring method. For example, the println method expects a String parameter, and a Product variable will be converted to a String variable using the tostring method. 20

Formatted Output Java provides a simple means of formatting output to a stream. This is a feature long known in the C language, and to some it has been conspicuous by its absence in Java. The System.out object offers a method format. The format method takes a formatting string as its first parameter, and then any number of objects after that. System.out.format ("%8d %s%n", 77, "Hello"); The call shown above produces the following note the leading spaces to observe an eight-character width for the numeric argument: 77 Hello The String class offers a format method as well. It takes the same parameters, but instead of producing the results to the console it returns a formatted string object. String representation = String.format ("%8d %s%n", 77, "Hello"); This provides a means of capturing formatted presentations and passing them around between objects. public String tostring () { return String.format ("(%d, %d)", x, y); 21

Formatting Strings The formatting string passed to format consists of literal text and fields. Each field in the string must correspond to an argument passed to the method with a few exceptional field types that produce special characters and don t need a value to be provided. Common field types are %d, which formats an integer %s, which formats a string %f, which formats a floating-point number %n, which produces an end-of-line sequence appropriate for the runtime operating system Most fields can be modified in a few simple ways: A number preceding the one-letter field code defines the field width, which is a minimum number of characters to be produced by the field. A hyphen preceding the number indicates the field will be leftjustified, where right-justified is the default, if a width has been specified even for strings. 22

Formatting Examples The following pairs of lines show the Java code to format certain values and the resulting output: System.out.format ("%d %s %s%n", 77, "Hi", "there"); 77 Hi there System.out.format ("%4d %8s %8s%n", 77, "Hi", "there"); 77 Hi there System.out.format ("%4d %-8s %-8s%n", 77, "Hi", "there"); 77 Hi there System.out.format ("%-16s $%,8.2f", "Dog bone", 70); Dog bone $ 70.00(and no line break!) System.out.format ("The value is $%,-1.2f.", 70); The value is $70.00. Formatted output is simple to use, but for many purposes it is still simpler and easier to simply print or println. Formatted output is especially helpful in establishing regular widths for fields, and in justifying the output text, so that columns of values are neatly aligned for the reader of the output. We will use a combination of the two practices in the rest of our code examples and exercises. 23

Using a Money Class LAB 7 Suggested time: 60 minutes In this lab you will create a Money class that can be used to hold and display currency values. The Money class will encapsulate formatting logic, hiding this detail from the rest of the program. Detailed instructions are found at the end of the chapter. 24

SUMMARY Classes are used in Java for representing structured data. An object is an instance of a class. Java classes support encapsulation through private member data and public methods. The new operator is used to instantiate objects from classes. Java uses references to refer to objects. An object without a reference represents unused memory, which will be cleaned up by garbage collection. Constructors are used to initialize objects. 25

Using a Money Class LAB 7 Introduction In this lab you will create a Money class that can be used to hold and display currency values. The Money class will encapsulate formatting logic, hiding this detail from the rest of the program. Directories: Money_Step0 (Exercise 1 work) Money_Step1 (Intermediate answer) Money_Step2 (Exercise 1 answer) Product_Step1 (Exercise 2 work) Product_Step2 (Exercise 2 answer) Instructions Exercise 1. Creating a Money Class Create a file src/money.java that defines a class to encapsulate storing and displaying a currency value. You are supplied a test program src/testmoney.java that can be used to exercise your class. Your class should have the following features: A private data member price of type double that is used as the internal representation. A constructor that initializes price from a double parameter that is passed in. An implementation of the standard tostring method that returns a string representation of a double used for currency value. Use String.format to get a currency representation that includes two digits to the right of the decimal point, and includes comma separators every three digits to the left of the decimal point. (See the final example of formatted output for the exact formatting field to use.) (This is the Step1 intermediate answer, and the one that s used in the next exercise.) run TestMoney $2.55 $15.50 $5,000.00 Optionally, try to make TestMoney produce clean columns of numbers, with the decimal points lined up. How about %,6.2f as a field, to accommodate up to 6-figure values? It doesn t quite work! If this is confusing, note that the digit to the left of the decimal point in a formatting field specifies the minimum width of the total field output that is, including commas, decimal point, and digits to the right. So six as a width only allows for six character columns not enough to accommodate the string $5,000.00 without breaking alignment. Try %,10.2f and see that you do get clean output, like this (and this is the Step2 final answer): 26

run TestMoney $ 2.55 $ 15.50 $ 5,000.00 Exercise 2. Using the Money Class in the Product Class In this exercise you will replace the internal representation of price in the Product class. You will use Money as the type of price in place of double. The external interface remains the same, so all calling programs should run unchanged. The Step1 version of Money.java has been placed in the src directory for this exercise. Try to make all the remaining changes on your own. If you get stuck you can refer to the following detailed list of the changes that you should make to src/product.java: 1. In the definition of the private data member price replace the type double by Money. 2. Modify the constructor to initialize price by instantiating a new Money object. 3. Modify the getprice method to return a Money. 4. Simplify the implementation of tostring to use the tostring method of Money. Note that you can get particularly elegant code by relying on Java to automatically convert a Money object to a String object, implicitly using the tostring method of Money. 5. Try to compile the program. You will find an error in adjustprice, because the operator += cannot be applied to the Money type. Go back to the Money class and implement a new method adjust which adds a double value to the internal price. Use this adjust method in adjustprice. 6. You should now be able to run the test program src/testproduct.java without making any changes. As a final enhancement you can simplify the test program by printing out all the string representations of products using the implicit invocation of tostring of Product class i.e. just call System.out.println(p1), etc. 27