+ All Categories
Home > Documents > 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

Date post: 13-Jan-2016
Category:
Upload: crystal-curtis
View: 217 times
Download: 2 times
Share this document with a friend
29
1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes
Transcript
Page 1: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

1

TCSS 143, Autumn 2004 Lecture Notes

Creating Java Classes

Page 2: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

2

Some terms

field: an instance variable; a variable inside an object

member: some entity belonging to an object, such as a field or method

instance: an object

type: a kind of variable; defined by a class

Page 3: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

3

What is an object?

State represented by object’s fields

Behavior represented by object’s methods

Identity represented by object itself, and its ability to

distinguish itself from similar objects

Page 4: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

4

Principles for designing a class

encapsulation: protecting private data of objects from outside tampering private state, public behavior

representation-independence: objects that aren’t locked in to a particular program or style of application (example: You should generally only call System.out.println from a static method)

Page 5: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

5

Public vs. private public: can be seen by all other classes

the class's name itself constructors, methods, constants

private: can be seen only within this class fields private "helper" methods, if needed note: other objects of same type can access

private fields of an object ("canine private")

rule of thumb: "private state, public behavior"

Page 6: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

6

Static vs. non-static Non-static (sometimes called virtual)

attached to an object, and exist / operate within the context of that object

affects the scope of what they can see and what they can do

there is one copy of every non-static member for each object of the type

Static members related to an entire class they are not attached to particular objects of that

class’s type there is only one copy of a static member: the class’s

copy

Page 7: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

7

Designing a class: fieldspublic class Person { private String myName; private int myPhoneNumber;

give fields clear names to differentiate them from local variables (recommended: use prefix 'my')

a variable should be made into a field if its state must persist past the end of any one method (all other variables can and should be local to the methods in which they are used)

should always be private to provide encapsulation a private field should have a get methods if it should be

accessible from outside, and a set method if it should be modifiable from outside

refer to a field as fieldname or this.fieldname

Page 8: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

8

Designing a class: static fields

public class Person {

public static final int SENIOR_CITIZEN_AGE = 65;

private static int ourPersonCount = 0;

data that is shared across the class should be stored in a static field (recommended: use prefix 'our')

not often used; usually such 'global variables' are a bad design!

public static fields are okay, but only if they are final (cannot be changed). No prefix, but USE_ALL_UPPER_CASE.

Refer to static field by its name (SENIOR_CITIZEN_AGE), in code inside the class; and by its classname.fieldname (Person.SENIOR_CITIZEN_AGE), in code outside the class.

Page 9: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

9

Designing a class: constructor

public class Person { // ... public Person(String name, int phoneNum) { myName = name; myPhoneNumber = phoneNum; ourPersonCount++; }

constructors should take all arguments necessary to initialize the object's state; no more, no less

a constructor should not do any heavy work, such as calling println to print state, or performing expensive computations

what if bad values are passed to a constructor? What state should the object have?

Page 10: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

10

Designing a class: methods

public class Person {

// ...

public boolean isOld() {

return myAge >= SENIOR_CITIZEN_AGE;

}

accessor method: allows you to see state of object generally its name begins with get, but not always (toString)

mutator method: allows you to modify the object a set method or method with side effects, such as setName or clear

avoid mutators that allow undesired setting of state

Page 11: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

11

Designing a class: static methods

public class PrimeNumber { // ... public static int[] sieve(int max) { // ... }

methods that perform general behavior related to the class, but do not depend on the state of any particular object, should be made static

rule of thumb: make it static when you can; but if you find yourself passing an instance of your class as an argument, likely it shouldn't be static, and should instead be a method of your object.

call a static method by its name (sieve), in code inside the class; and by its classname.methodname (PrimeNumber.sieve), in code outside the class.

Page 12: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

12

Evaluating designs: "The 'C's"

cohesion: Do the things in your class go together? completeness: Are any major concepts missing?

Does this class represent just a partial concept? convenience: Is the class easy enough to use? clarity: Can someone else understand the class? consistency: Are the naming conventions and

behavior the same between all classes and methods?

coupling: Are many classes tied to each other? coupling is bad; the rest of the above are good!

Page 13: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

13

Class design practice problem

Design a class BankAccount to model users' bank accounts. The account should keep a user's ID and balance, accurate to the nearest cent. The user should be able to make deposits and withdrawals on his/her account, as well as changing the account's ID at any time. The balance must stay non-negative.

Also, since bank accounts might be used as part of a larger bank system, the system needs to be able to find out how many BankAccounts have been created in total.

Page 14: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

14

Java's Object class the most basic type of object in Java

basis for all other types (excluding primitives)

defines basic behavior that all objects will have(in other words, no matter what class you are dealing with, you are guaranteed that its objects have these methods)

the behaviors of these methods are usually not useful unless you write your own version in your class

Page 15: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

15

Methods in class Object protected Object clone()

Returns a copy of this Object.

public boolean equals(Object obj)Returns whether or not object obj is "equal to" this one.

protected void finalize()Called by the garbage collector when it is time to collect this object.

public Class getClass()Returns information about the class this object belongs to.

public int hashCode()Used by some data structures to create an integer code for this object.

Page 16: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

16

More Object methods public String toString()

Returns a string representation of this object.

public void notify() public void notifyAll() public void wait() public void wait(long timeout) public void wait(long timeout, int nanosec)

Methods related to concurrent programming; these methods allow threads to "wait for" signals from each other by attaching themselves to important objects. (We won't use them.)

Page 17: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

17

Printing objects: toString

toString provides a string representation of a Java object

primarily used to print objects on the console with System.out.println

Sun's Java style guidelines suggest implementing a toString method for every class you write

Page 18: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

18

toString practice problems

Add a toString method to BankAccount so that BankAccount objects will print in this format:

Marty Stepp, $142.50

Add a toString method to Person so that Person objects will print in this format:

Rich Mercen: (253) 123-4567

Page 19: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

19

Object equality test: equals

Default equals method (from Object) checks for referential equality; must literally refer to

the same object (identical to behavior of == operator)

Desired result: check for state equivalence (where they may refer to two different objects, but they have the same state)

Advantages of overriding equals correct behavior in collections (can find elements) more accurate comparison of objects

Page 20: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

20

Overriding equals

Conditions for overriding equals correctly: reflexive: for any object x, the test x.equals(x) should return true

symmetric: if and only if x.equals(y), then y.equals(x)

transitive: if x.equals(y) and y.equals(z),then x.equals(z)

(taken together, a relationship with these three properties is called an equivalence relation)

Page 21: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

21

Overriding equals, cont'd. Things to do in a good equals implementation

handle null case (should return false) optimize the trivial case, when this == obj

(should return true)

public boolean equals(Object obj) {

if (this == obj) {

return true;

} else if (obj == null) {

return false;

} else { /* compare them and return answer */ }

}

Page 22: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

22

equals practice problems

Add an equals method to Person so that persons will be considered equal only if they have exactly the same name and phone number.

Should we add equals to BankAccount? Why or why not?

Page 23: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

23

Comparing objects: compareTo

many types of objects have a natural ordering, a way to compare them and put them in some kind of order

in Java, objects that have a natural ordering have a method compareTo that compares two objects

advantage: can compare objects, organize or sort objects in a collection or array

some classes that have compareTo:String, Date, File, URI

Page 24: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

24

The method compareTo

public int compareTo(Object o)

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

In summary: negative integer: this object is less than o zero: this object is equal to o positive integer: this object is greater than o

Page 25: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

25

compareTo usage examples

String marty = "Marty Stepp";

String jill = "Jill Jackson";

String amy = "Amy Clump";

marty.compareTo(marty) == ______

marty.compareTo(jill) == ______

amy.compareTo(jill) == ______

jill.compareTo(amy) == ______

jill.compareTo("Jill Jackson") == ______

amy.compareTo("Amy Smith") == ______

Page 26: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

26

compareTo examplepublic class Person { private String myName; private int myPhoneNumber;

/* Compares Person objects by name, breaking ties by phone number. */ public int compareTo(Object o) { Person p = (Person)o; int nameCmp = myName.compareTo(p.getName()); if (nameCmp != 0) return nameCmp; else return myPhoneNumber - p.getPhoneNumber();} }

Page 27: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

27

compareTo practice problems Make the class Fraction, as defined by

instructor's Fraction.java, comparable. The compareTo method should return -1 if this fraction is less than the argument, 0 if they are equal, or 1 if this fraction is greater than the argument. Note that two fractions should be considered equal if they have the same value. This means, for example, that the fraction 2/3 should be considered equal to the fraction 4/6.

Re-implement equals for class Person, taking advantage of an existing compareTo method.

Page 28: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

28

compareTo search / sorting

if the objects of your class are comparable, Java can sort an array of them using Arrays.sort, or a list of them using Collections.sort (seen later)

practice problem: Write a static method isSorted that accepts an array of Fractions as its argument, and returns true if the Fractions in the array are stored in ascending order by value, and false if not.

Page 29: 1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.

29

References

Koffman, Chapter 1, pp. 11-13;Appendix A, pp. 700-710


Recommended