cs102--object oriented programming lecture 3: – defining classes (10 questions) – the...

62
CS102--Object Oriented Programming • Lecture 3: – Defining classes (10 questions) – The StringTokenizer class – The Math class Copyright © 2008 Xiaoyan Li

Post on 21-Dec-2015

229 views

Category:

Documents


0 download

TRANSCRIPT

CS102--Object Oriented Programming

• Lecture 3:

– Defining classes (10 questions)

– The StringTokenizer class– The Math class

Copyright © 2008 Xiaoyan Li

Review:

• The String class• Console output/input

– System.out.print– System.out.println– System.out.printf– The Scanner class

• Flow of control– Branching– looping

Ten Important Questions about Classes in java:

• 1. What are the contents of a class?• 2. Where are they placed within a class?• 3. What are instance variables and local variables?• 4. What is the difference between primitive type values and

class type values?• 5. Which operator do you need to create an object?• 6. What is the meaning of the reserved word “this”?• 7. When do you use the modifier public or private?• 8. What is a constructor? How many constructors can a class

have?• 9. What are static methods and static variables?• 10. What are reference variables and value variables?

Defining Classes: The Contents of a Class Definition

• A class definition specifies the data items and methods that all of its objects will have

– These data items and methods are sometimes called members of the object

– Data items are called fields or instance variables

• Where can instance variable declarations and method definitions be placed within the class definition– Anywhere and in any order

• Local variables vs. instance variables

4-4Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Primitive Type Values vs. Class Type Values

• A primitive type value is a single piece of data• A class type value or object can have multiple pieces

of data, as well as actions called methods– All objects of a class have the same methods– All objects of a class have the same pieces of data (i.e.,

name, type, and number)– For a given object, each piece of data can hold a different

value

4-5Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The new Operator

• An object of a class is named or declared by a variable of the class type: ClassName classVar;

• The new operator must then be used to create the object and associate it with its variable name: classVar = new ClassName();

• These can be combined as follows: ClassName classVar = new ClassName();

4-6Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Instance Variables and Methods• Instance variables can be defined as in the following

two examples– Note the public modifier (for now): public String instanceVar1; public int instanceVar2;

• In order to refer to a particular instance variable, preface it with its object name as follows:objectName.instanceVar1objectName.instanceVar2

4-7Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The this Parameter

• All instance variables are understood to have <the calling object>. in front of them

• If an explicit name for the calling object is needed, the keyword this can be used– myInstanceVariable always means and is always

interchangeable with this.myInstanceVariable

4-8Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The methods equals and toString

• Java expects certain methods, such as equals and toString, to be in all, or almost all, classes

• The purpose of equals, a boolean valued method, is to compare two objects of the class to see if they satisfy the notion of "being equal"– Note: You cannot use == to compare objects public boolean equals(ClassName objectName)

• The purpose of the toString method is to return a String value that represents the data in the object public String toString()

4-9Copyright © 2008 Pearson Addison-Wesley. All rights reserved

public and private Modifiers• The modifier public means that there are no restrictions on

where an instance variable or method can be used• The modifier private means that an instance variable or

method cannot be accessed by name outside of the class• It is considered good programming practice to make all

instance variables private• Most methods are public, and thus provide controlled

access to the object• Usually, methods are private only if used as helping

methods for other methods in the class

4-10Copyright © 2008 Pearson Addison-Wesley. All rights reserved

A Class Has Access to Private Members of All Objects of the Class

• Within the definition of a class, private members of any object of the class can be accessed, not just private members of the calling object

4-11Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Overloading

• Overloading is when two or more methods in the same class have the same method name

• To be valid, any two definitions of the method name must have different signatures– A signature consists of the name of a method together

with its parameter list– Differing signatures must have different numbers

and/or types of parameters

4-12Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Overloading and Automatic Type Conversion

• If Java cannot find a method signature that exactly matches a method invocation, it will try to use automatic type conversion

• The interaction of overloading and automatic type conversion can have unintended results

• In some cases of overloading, because of automatic type conversion, a single method invocation can be resolved in multiple ways– Ambiguous method invocations will produce an error in

Java

4-13Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Constructors

• A constructor is a special kind of method that is designed to initialize the instance variables for an object:public ClassName(anyParameters){code}– A constructor must have the same name as the class– A constructor has no type returned, not even void– Constructors are typically overloaded

4-14Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Constructors

• A constructor is called when an object of the class is created using newClassName objectName = new ClassName(anyArgs);– The name of the constructor and its parenthesized list of

arguments (if any) must follow the new operator – This is the only valid way to invoke a constructor: a constructor

cannot be invoked like an ordinary method• If a constructor is invoked again (using new), the first

object is discarded and an entirely new object is created– If you need to change the values of instance variables of the

object, use mutator methods instead

4-15Copyright © 2008 Pearson Addison-Wesley. All rights reserved

You Can Invoke Another Method in a Constructor

• The first action taken by a constructor is to create an object with instance variables

• Therefore, it is legal to invoke another method within the definition of a constructor, since it has the newly created object as its calling object– For example, mutator methods can be used to set the

values of the instance variables– It is even possible for one constructor to invoke another

4-16Copyright © 2008 Pearson Addison-Wesley. All rights reserved

A Constructor Has a this Parameter

• Like any ordinary method, every constructor has a this parameter

• The this parameter can be used explicitly, but is more often understood to be there than written down

• The first action taken by a constructor is to automatically create an object with instance variables

• Then within the definition of a constructor, the this parameter refers to the object created by the constructor

4-17Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Include a No-Argument Constructor

• If you do not include any constructors in your class, Java will automatically create a default or no-argument constructor that takes no arguments, performs no initializations, but allows the object to be created

• If you include even one constructor in your class, Java will not provide this default constructor

• If you include any constructors in your class, be sure to provide your own no-argument constructor as well

4-18Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Static Methods• A static method is one that can be used without a calling

object• A static method still belongs to a class, and its definition is

given inside the class definition• When a static method is defined, the keyword static is

placed in the method headerpublic static returnedType myMethod(parameters) { . . . }

• Static methods are invoked using the class name in place of a calling objectreturnedValue = MyClass.myMethod(arguments);

5-19Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Static Variables• A static variable is a variable that belongs to the class as a

whole, and not just to one object– There is only one copy of a static variable per class, unlike instance

variables where each object has its own copy• All objects of the class can read and change a static variable• Although a static method cannot access an instance variable,

a static method can access a static variable• A static variable is declared like an instance variable, with the

addition of the modifier staticprivate static int myStaticVariable;

5-20Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Static Variables

• A static variable should always be defined private, unless it is also a defined constant– The value of a static defined constant cannot be altered,

therefore it is safe to make it public– In addition to static, the declaration for a static defined

constant must include the modifier final, which indicates that its value cannot be changed

public static final int BIRTH_YEAR = 1954;

• When referring to such a defined constant outside its class, use the name of its class in place of a calling object

int year = MyClass.BIRTH_YEAR;

5-21Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Variables and Memory

• A computer has two forms of memory• Secondary memory is used to hold files for

"permanent" storage• Main memory is used by a computer when it is

running a program– Values stored in a program's variables are kept in

main memory

5-22Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Variables and Memory

• Main memory consists of a long list of numbered locations called bytes– Each byte contains eight bits: eight 0 or 1 digits

• The number that identifies a byte is called its address– A data item can be stored in one (or more) of these bytes– The address of the byte is used to find the data item when

needed

5-23Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Variables and Memory• Values of most data types require more than one

byte of storage– Several adjacent bytes are then used to hold the data item– The entire chunk of memory that holds the data is called

its memory location– The address of the first byte of this memory location is

used as the address for the data item• A computer's main memory can be thought of as a

long list of memory locations of varying sizes

5-24Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Variables in Memory

5-25Copyright © 2008 Pearson Addison-Wesley. All rights reserved

References

• Every variable is implemented as a location in computer memory

• When the variable is a primitive type, the value of the variable is stored in the memory location assigned to the variable– Each primitive type always require the same amount of

memory to store its values

5-26Copyright © 2008 Pearson Addison-Wesley. All rights reserved

References• When the variable is a class type, only the memory address

(or reference) where its object is located is stored in the memory location assigned to the variable– The object named by the variable is stored in some other location in

memory

– Like primitives, the value of a class variable is a fixed size

– Unlike primitives, the value of a class variable is a memory address or reference

– The object, whose address is stored in the variable, can be of any size

5-27Copyright © 2008 Pearson Addison-Wesley. All rights reserved

References

• Two reference variables can contain the same reference, and therefore name the same object– The assignment operator sets the reference (memory

address) of one class type variable equal to that of another– Any change to the object named by one of theses variables

will produce a change to the object named by the other variable, since they are the same objectvariable2 = variable1;

5-28Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Class Type Variables Store a Reference (Part 1 of 2)

5-29Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Class Type Variables Store a Reference (Part 2 of 2)

5-30Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Assignment Operator with Class Type Variables (Part 1 of 3)

5-31Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Assignment Operator with Class Type Variables (Part 2 of 3)

5-32Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Assignment Operator with Class Type Variables (Part 3 of 3)

5-33Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Class Parameters

• All parameters in Java are call-by-value parameters– A parameter is a local variable that is set equal to the

value of its argument– Therefore, any change to the value of the parameter

cannot change the value of its argument• Class type parameters appear to behave

differently from primitive type parameters– They appear to behave in a way similar to parameters

in languages that have the call-by-reference parameter passing mechanism

5-34Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Class Parameters

• The value plugged into a class type parameter is a reference (memory address)– Therefore, the parameter becomes another name for

the argument– Any change made to the object named by the

parameter (i.e., changes made to the values of its instance variables) will be made to the object named by the argument, because they are the same object

– Note that, because it still is a call-by-value parameter, any change made to the class type parameter itself (i.e., its address) will not change its argument (the reference or memory address)

5-35Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Parameters of a Class Type

5-36Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Public static void changer(ToyClass aparameter){

aParameter.name =“Hot Shot”;aParameter.number = 42;

}

The changer method in ToyClass

Memory Picture for Display 5.14 (Part 1 of 3)

5-38Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Memory Picture for Display 5.14 (Part 2 of 3)

5-39Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Memory Picture for Display 5.14 (Part 3 of 3)

5-40Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Differences Between Primitive and Class-Type Parameters

• A method cannot change the value of a variable of a primitive type that is an argument to the method

• In contrast, a method can change the values of the instance variables of a class type that is an argument to the method

5-41Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Comparing Parameters of a Class Type and a Primitive Type (Part 1 of 2)

5-42Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Comparing Parameters of a Class Type and a Primitive Type (Part 2 of 2)

5-43Copyright © 2008 Pearson Addison-Wesley. All rights reserved

A Toy Class to Use in Display 5.16 (Part 1 of 2)

5-44Copyright © 2008 Pearson Addison-Wesley. All rights reserved

A Toy Class to Use in Display 5.16 (Part 2 of 2)

5-45Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Copy Constructors• A copy constructor is a constructor with a single

argument of the same type as the class• The copy constructor should create an object that is

a separate, independent object, but with the instance variables set so that it is an exact copy of the argument object

• Note how, in the Date copy constructor, the values of all of the primitive type private instance variables are merely copied

5-46Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Copy Constructor for a Class with Primitive Type Instance Variables

public Date(Date aDate){ if (aDate == null) //Not a real date. { System.out.println("Fatal Error."); System.exit(0); }

month = aDate.month; day = aDate.day; year = aDate.year;}

5-47Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Copy Constructor for a Class with Class Type Instance Variables

• Unlike the Date class, the Person class contains three class type instance variables

• If the born and died class type instance variables for the new Person object were merely copied, then they would simply rename the born and died variables from the original Person object

born = original.born //dangerousdied = original.died //dangerous

– This would not create an independent copy of the original object

5-48Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Mutable and Immutable Classes

• A class that contains no methods (other than constructors) that change any of the data in an object of the class is called an immutable class– Objects of such a class are called immutable objects– It is perfectly safe to return a reference to an immutable

object because the object cannot be changed in any way– The String class is an immutable class

5-49Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Mutable and Immutable Classes

• A class that contains public mutator methods or other public methods that can change the data in its objects is called a mutable class, and its objects are called mutable objects– Never write a method that returns a mutable object– Instead, use a copy constructor to return a reference to a

completely independent copy of the mutable object

5-50Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Deep Copy Versus Shallow Copy

• A deep copy of an object is a copy that, with one exception, has no references in common with the original– Exception: References to immutable objects are allowed

to be shared

• Any copy that is not a deep copy is called a shallow copy– This type of copy can cause dangerous privacy leaks in a

program

5-51Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Exercise: What is the output of the following code?

Date date1 = new Date(“January”,1,2006);Date date2;date2 = date1;System.out.println(date2);date2.setDate(“July”,4, 1776);System.out.println(date1);System.out.println(date2);

Date date1 = new Date(“January”,1,2006);Date date2;date2 = new Date(date1);System.out.println(date2);date2.setDate(“July”,4, 1776);System.out.println(date1);System.out.println(date2);

Code A

Code B

The StringTokenizer Class

• The StringTokenizer class is used to recover the words or tokens in a multi-word String– You can use whitespace characters to separate each

token, or you can specify the characters you wish to use as separators

– In order to use the StringTokenizer class, be sure to include the following at the start of the file:

import java.util.StringTokenizer;

4-53Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the StringTokenizer Class (Part 1 of 2)

4-54Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the StringTokenizer Class (Part 2 of 2)

4-55Copyright © 2008 Pearson Addison-Wesley. All rights reserved

The Math Classhttp://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html

• The Math class provides a number of standard mathematical methods– It is found in the java.lang package, so it does not

require an import statement– All of its methods and data are static, therefore they are

invoked with the class name Math instead of a calling object

– The Math class has two predefined constants, E (e, the base of the natural logarithm system) and PI (, 3.1415 . . .)area = Math.PI * radius * radius;

5-56Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Math (Part 1 of 5)

5-57Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Math (Part 2 of 5)

5-58Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Math (Part 3 of 5)

5-59Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Math (Part 4 of 5)

5-60Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Some Methods in the Class Math (Part 5 of 5)

5-61Copyright © 2008 Pearson Addison-Wesley. All rights reserved

Announcement:• Programming assignment 1:

– Page 92: project 9. Page 160: project 3.• Due date:

– Thursday, Feb 14th. Late work may be submitted on Friday or Saturday with 5% penalty per day. No work will be accepted after Saturday.

• How to turn in: – Email your files (both .java & .class files) to TA and me with “cs102

assignment1” in your message subject line.• Grading.

– Correctness: 80 points.– Readability: 20 points.