chapter 4: defining classes 1 1. 1.writing our own classes 1.1 instance variables 1.2 methods 2.some...

85
Chapter 4: Defining Classes 1 1

Upload: coral-thornton

Post on 05-Jan-2016

220 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

Chapter 4: Defining Classes 1

1

Page 2: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

1. Writing our own classes1.1 Instance Variables1.2 Methods

2. Some notions of OOP3. Passing and returning objects4. Recap

2

Page 3: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

programmers can: use pre-defined classes develop their own classes

a class library is a collection of pre-defined classes

the Java standard class library (or Java API - Application Programming Interface) defines many classes ex:

the System class the String class

3

Page 4: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

So far, our program had only 1 class with 1 method (main)

For large problems… the program becomes large and difficult to understand repetition of instructions, variables are dispersed…

Solution: decompose the problem in sub-problems easier to implement

into methods group related variables and methods into classes

4

public class MyProgram {

}

public static void main (String[] args)

{

}

Page 5: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

Class: a blueprint/model/pattern to create objects specified by:

state - descriptive characteristics behaviors - what it can do (or what can be done to it)

Object: a specific variable of a class (an instance)

5

class objects

Date

Book

PlayingCard

Planet

Page 6: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

6

Class State Behavior

Date

library book

bank account

Page 7: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

A class contains: data declarations

(state) method declarations

(behavior)

7

int x, y;char ch;

Data declarations

Method declarations

Page 8: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

data (state) day month year

methods (behavior): nextDay isWeekend isMyBirthday printDate …

8

Page 9: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

in general, we store each class in its own file

the program is now made of at least 2 files:1. the class definition file:

defines the data and methods of a class ex: DateFirstTry.java

2. the driver file: contains the main method declares and uses objects of the class controls the use of other parts of a program often used to test other parts of the program ex: DateFirstTryDemo.java

9

Page 10: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

public class Date{ private String month; private int day; private int year;

public Date nextDay () { … }

public boolean isWeekEnd () { … }

public void printDate() { ... }

}

10

Date.java

Method declarations (behavior)

Data declarations (state)

Page 11: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

public class DateFirstTryDemo{ public static void main(String[] args) {

Date date1, date2; date1 = new Date(); date2 = new Date();

if (date1.isWeekEnd()) System.out.print("yuppi");

date1.printDate( );

if (date2.isWeekEnd()) System.out.print("good");

}}

11

DateFirstTryDemo.java

usage of the 2 objects

declaration of 2 objects

Page 12: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

syntax:nameOfClass nameOfObject = new nameOfClass();

nameOfClass nameOfObject ;

nameOfObject = new nameOfClass();

ornameOfClass nameOfObject = new nameOfClass(parameter list);

nameOfClass nameOfObject;

nameOfObject = new nameOfClass(parameter list);

12

Coin myCoin = new Coin();

String aString = new String("the content of the string");

BankAccount account123 = new BankAccount();BankAccount account555 = new BankAccount();

this calls a method called the constructor… will see later

Page 13: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

The new operator:A. allocates memoryB. is used to create an object of a classC. associates an object with a variable that names

it.D. All of the above.

13

Page 14: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

variables/constants declared inside the class but not inside a specific method

also called attributes can be used by any method of the class initialized to 0 (false for booleans) each object (instance) of the class has its own instance data

Example:

14

double bal;

class BankAccount

bal 0

ac1

bal 0

ac2

BankAccount ac1=new BankAccount(); BankAccount ac2=new BankAccount();

Page 15: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

implement the behavior of all objects of a particular class

all objects of a class share the method definitions some methods are a bit special…

(ex: constructor, toString, equals…)

group of statements that are given a name easier to decompose the problem into sub-

problems that are easier to implement a method is defined once, but can be used

(called/invoked) several times

15

Page 16: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

method header + method body

syntax:

ex:

16

method body

method header

{ statements of the method}

visibility static returnType methodName(listOfParameters)

optional

public void sayHi() { System.out.print("Hi");}

public static void main(String[] args) { …}

Page 17: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

to access any members (data or method) within the class

nameOfData nameOfMethod(actualParameters)

from outside the class non-static:

nameOfObject.nameOfData nameOfObject.nameOfMethod(actualParameters)

static: nameOfClass.nameOfData nameOfClass.nameOfMethod(actualParameters)

17

Page 18: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

public class Coin{ private final int HEADS = 0; private final int TAILS = 1; private int face;

public void flip() { _______= (int)(Math.random()*2); }

public boolean isHeads() { return (_______ == HEADS); }

// flips the coin 5 times public void flip5() { for (int i=1; i<=5; i++)

___________________ }…

}

18class def.

Page 19: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

public class Coin{ private final int HEADS = 0; private final int TAILS = 1; private int face;

public void flip() { _______= (int)(Math.random()*2); }

public boolean isHeads() { return (_________ == HEADS); }

// flips the coin 5 times public void flip5() { for (int i=1; i<=5; i++)

___________________ }…}

19

class def.

public class FlipRace{ public static void main (String[] args) { final int GOAL = 3; int count1 = 0, count2 = 0;

// Create two separate coin objects Coin coin1 = new Coin(); Coin coin2 = new Coin();

// Flip the coins and count heads while (count1<GOAL && count2<GOAL) { ____________________________;

____________________________;

if (coin1.isHeads()) count1++; if (coin2.isHeads()) count2++; } flip(); // 1. ok? coin1.flip; // 2. ok? … }}

driver

Page 20: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

When a method is invoked:1. the current method is suspended2. the called method is executed3. when completed, the flow returns to the place where the

method was called and resumes its execution

20

doIt

helpMe

helpMe();

obj.doIt();

main

Car.javadriver

Car obj;obj = new Car();

Page 21: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

There are two kinds of methods: Methods that compute and return a value

Methods that perform an action does not return a value is called a void method

21

Page 22: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

similar to a math function must specify the type of that value in its heading: public typeReturned methodName(paramList)

Examples: description: determines if the coin is a tail (1==tail,

0==heads) name: isTail result: boolean

description: returns the value of the face name: getFace result: int

22

public boolean isTail(){ if (face == 1) return true; else return false;}

public int getFace() { return (face);}

Page 23: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

allows the method to "return" a result syntax: return expression;

1. the expression is evaluated2. the value of the expression is returned as the result of the method

3. the method is exited

23

public boolean isTail(){ if (face == 1) return true; else return false;}

public boolean isTail(){ return (________________________);}

public int getFace() { return (face);}

Another way of writing the method isTail() is …. ?

Page 24: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

they perform an action performed, but do not “evaluate” to a value ex: they display something, change the value of an attribute, …

they officially return void they use no return expression;

either: return; or nothing…

24

public void flip() { face = (int)(Math.random()*2);}

public void flip() { face = (int)(Math.random()*2); return;}

public ___ printFace() { System.out.print(face);}

Page 25: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

methods that return a result are expressions that have: a type and a value

methods that do not return a result are not expressions you call them with the statement: objectName.methodName();

25

public class Driver { public static void main (String[] args) { Coin coin1 = new Coin(); boolean result; coin1.flip(); // 1. ok? result = coin1.flip(); // 2. ok? if (coin1.flip()) // 3. ok? System.out.print("whatever"); System.out.print(coin1.flip()); // 4. ok? }}

driver

Page 26: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

Which one of these statements is syntactically correct?Coin coin1 = new Coin();boolean result;1. coin1.isTail(); 2. result = coin1.isTail(); 3. if (coin1.isTail())

System.out.print("whatever"); 4. System.out.print(coin1.isTail());

A. All are syntactically correctB. 2. and 3. only are syntactically correctC. 2., 3. and 4. only are syntactically correctD. 1. is the only one which is syntactically correctE. 3. is the only one which is syntactically correct

26

Page 27: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

27

Page 28: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

28

The body of a method that returns a value must contain at least one _________ statement.

A. voidB. invocation statementC. declarationD. return

Page 29: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

Local variables: declared inside a method

variable that is necessary for that method only method parameters are considered local

variables

If 2 methods have a local variable of the same name, they are 2 entirely different variables

Global variables: Java does not have global variables

29

Page 30: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

Some methods need to receive additional data in order to perform their work allows the function to be more generic

ex. sqrt method works for any doubleMath.sqrt(9), Math.sqrt(15.5), Math.sqrt(75),...

Definitions: formal parameter:

parameter specified in the method header argument or actual/run-time parameter:

parameter specified in the method call / invocation

30

Page 31: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

public class Account

{

private double balance;

public void deposit (double theAmount)

{

if (theAmount < 0) // deposit value is negative

System.out.println ("Error: Deposit amount is invalid.");

else

balance = balance + theAmount;

}

31

public class Banking{ public static void main (String[] args) { Account acct1 = new Account(); acct1.deposit(25.85); acct1.deposit(10); }}

class def.

driver

Page 32: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

32

Page 33: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

public class Store{ public void printPrice(String itemName, double p) { System.out.println (“The " + itemName + " costs " + p); }}

33

public static void main (String[] args){ Store myStore = new Store(); myStore.printPrice("desk", 300.99);

double special = 195.99; myStore.printPrice("chair", special);

Store yourStore = new Store(); double p = Keyboard.nextDouble(); String s = "desk"; yourStore.printPrice(s, Math.min(100, p));}

class def.

driver

The desk costs 300.99

The chair costs 195.99

99

The desk costs 99.0

output

Page 34: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

in the class Account…

write the header of the methods: withdraw: getInterestRate: changeName:

34

public class Account{ private long acctNumber; private double balance; private String name; private double interestRate; …

Page 35: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

public class AccountTest { public static void main(String[] args) { Account A1 = new Account(); A1.widthraw(123456, 5000.0); A1.changeName(“NewName”);

A1.getInterestRate(); } }

35

In a driver class… write instructions to create an account and call the previous methods

Page 36: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

A variable whose meaning is confined to an object of a class is called:

A. instance variableB. local variableC. global variableD. none of the above

36

Page 37: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

A variable whose meaning is confined to a method definition is called an/a

A. instance variableB. local variableC. global variableD. none of the above

37

Page 38: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

when a method is called: the actual parameters are copied into the formal

parameters the method works with a copy of the actual parameters … when we return from the function, the actual

parameters are unchanged

38

public void someMethod(int num1, int num2, String message)

{ …}

someMethod(25, count, "Hello");

Page 39: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

public class SomeClass{ private double someAttribute;

public void someMethod(int someParam) { System.out.println(someParam); if (someParam < 0) someParam = 0; someAttribute = someParam;

System.out.println(someParam); }}

39

public class SomeDriver{ public static void main(String[] args) { SomeClass someObj=new SomeClass(); int someVar = -100;

System.out.println(someVar); someObj.someMethod(someVar); System.out.println(someVar); }}

class def.

driver

-100-1000-100

output

Page 40: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

when a method is called: the order of the actual param. must be == to the order of the formal

param. the nb of actual param. must be == to the nb of formal param. the types of the actual param. must be compatible with the types of

the formal param.

40

public class Test{ … public void aMethod(String a, long b, double c, char d, boolean e) {…}…

public class Driver {Test myTest = new Test();

myTest.aMethod("hello", 10, 15.5, 'a', 'a' == 'b'); // 1. OK? Yes myTest.aMethod("hello", 10.5, 15, 'a', true); // 2. OK? ===> No because of 10.5 is double…

class def.

driver

Page 41: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

41

public class Test{ … public void aMethod(String a, long b, double c, char d, boolean e) {…}…

public class Driver {Test myTest = new Test();myTest.aMethod("hello", 10, 15);// invalid : ("hello“, 10, 15, 0, false)

class def.

driver

Given the following class definition

The following statement in the driver is

A. ValidB. Invalid, because number of actual & formal

parameters don’t matchC. Invalid, because the type of actual & formal

parameters don’t match

Page 42: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

42

public class Test{ … public void aMethod(String a, long b, double c, char d, boolean e) {…}…

public class Driver {Test myTest = new Test();myTest.aMethod("hello", 10, 15, 67, true);

class def.

driver

Given the following class definition

The following statement in the driver is

A. ValidB. Invalid, because number of actual & formal

parameters don’t matchC. Invalid, because the type of actual & formal

parameters don’t match

Page 43: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

43

public class Test{ … public void aMethod(String a, long b, double c, char d, boolean e) {…}…

public class Driver {Test myTest = new Test();myTest.aMethod("hello", 10, 15, (char)67, true);

class def.

driver

Given the following class definition

The following statement in the driver is

A. ValidB. Invalid, because number of actual & formal

parameters don’t matchC. Invalid, because the type of actual & formal

parameters don’t match

Page 44: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

the types of the actual param. must be compatible with the types of the corresponding formal param.

public double myMethod(int p1, int p2, double p3) {…}…int a=1,b=2,c=3;double result = myMethod(a,b,c);

If no exact type match --> automatic type conversion c is casted to a double remember: byteshortintlongfloatdouble char

44

Page 45: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

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

inside a method: myInstanceVariable is identical to this.myInstanceVariable

45

public void deposit(int amount){ balance += amount; this.balance += amount;}

Page 46: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

this must be used: if a parameter or other local variable has the

same name as an instance variable otherwise, the local variable will be used

46

public class Account { private double balance;

public void initialize(double balance) { this.balance = balance; }} localinstance

Page 47: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

when an entire object is printed…

the toString method is automatically called if you have not defined a toString method, then

otherwise, define your own version of toString for your object

47

public class Banking{ public static void main (String[] args) { Account acct1 = new Account("Ted", 123, 100.0);

acct1.deposit (25.55);

System.out.println(acct1); }}

Account@182f0db

driver

Page 48: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

48

Defining your own toString()

public class Account{ private long acctNumber; private double balance; private String name;

public Account(String owner, long account, double initial) { … }

// Returns a one-line description of the account as a string.

public String toString(){ return (acctNumber + "\t" + name + "\t" + balance); }…

toString() must: take no parameter return a string object

class def.123 Ted 125.55

Page 49: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

to compare two objects, you can use: == operator

compares equality of references returns true:

if the references point to the same object NOT if the objects pointed have the same content

equals() method compares equality of the content of the objects returns true:

if the references point objects that have the same content

49

if (myAccount == yourAccount) System.out.print("same object");

if (myAccount.equals(yourAccount)) System.out.print("same content");

Page 50: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

The method equals : is defined for all objects unless we redefine it in our class, it has the same semantics as

== we can redefine it to return true under whatever conditions we

think are appropriate (ex. equality of content, not address)

50

public class Account { private String name; private double balance; private int acctNumber;

boolean equals(Account anotherAccount) {

}…

Page 51: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

EqualsAndToStringDemo.java

DateFourthTry.java

51

Page 52: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

52

CONSTRUCTORS Assume:

to initialize an object, we can do:

public class BankAccount{ private String name; private long acctNumber; private double balance; public void initialize(String theOwner, long theAccount, double theInitial) { name = theOwner; acctNumber = theAccount; balance = theInitial; }… BankAccount.java

BankAccount account123 = new BankAccount();account123.initialize("ted", 123, 100);

BankAccount account555 = new BankAccount();account123.initialize("mary", 555, 300);

driver

Page 53: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

53

a constructor is a special method that: is called automatically called when an object of the class is

declared is usually used to initialize the data of an object

must have the same name as the class name has no return type (not even void) must be public

can have parameters

If you do not define any constructor in your class, a default constructor that initializes instance variables to 0

BankAccount account123 = new BankAccount("ted", 123, 100);

BankAccount account555 = new BankAccount("mary", 555, 300);

Page 54: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

public class BankAccount{ private long acctNumber; private double balance; private String name; // a constructor:

public BankAccountBankAccount(String theOwner, long theAccount, double theInitial)

{ name = theOwner; acctNumber = theAccount; balance = theInitial; }

public void deposit(double amount) { … } public void withdraw(double amount) { … } …}

54

Example 1

BankAccount.java

Page 55: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

public class Coin{ private final int HEADS = 0; private final int TAILS = 1; private int face;

public Coin() { flip(); }

public void flip() { face = (int)(Math.random()*2); }

public boolean isHeads() { return (face == HEADS); }…}

55

Example 2public class CountFlips{ public static void main (String[]

args) { Coin myCoin = new Coin(); Coin anotherCoin = new Coin(); Coin athirdCoin = new Coin();

… }}

Coin.java

driver

Page 56: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

Date.java

ConstructorsDemo.java

56

Page 57: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

If you do not include any constructors in your class, Java will automatically create a default or no-argument

constructor

The default constructor: takes no arguments initializes all instance variables to zero (null or false) but allows the object to be created

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

57

Page 58: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

overloading = same name is used to refer to different things "chair" (person or furniture) / (integer or real division)

overloaded methods: several methods have the same name but different definitions

the signature of each overloaded method must be unique signature = name of method + parameter list the compiler determines which version of the method is being

invoked by analyzing the signature the return type of the method is not part of the signature

58

Page 59: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

59

public int increment(int x){ return x+1;}

Version 1public int increment(int x, int value){ return x+value;}

Version 2

int result = 1;

result = increment(20, 4); // 1. ok?

result = increment(10); // 2. ok?

result = increment(result); // 3. ok?

result = increment(result, result); // 4. ok?

Invocations

Page 60: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

60

public int increment(int x){ return x+1;}

Version 1public int increment(int x, int value){ return x+value;}

Version 2

int result = 1;

result = increment(result, result, result);

Invocations

A. ValidB. Invalid, wrong number of argumentsC. Invalid, wrong type of arguments

Page 61: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

61

public int increment(int x){ return x+1;}

Version 1public int increment(int x, int value){ return x+value;}

Version 2

int result = 1;

result = increment(result, increment(result, result));

Invocations

A. ValidB. Invalid, wrong number of arguments,C. Invalid, wrong type of arguments.

Page 62: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

62

public int increment(int x){ return x+1;}

Version 1public int increment(int x, int value){ return x+value;}

Version 2

int result = 1;

result = increment();

Invocations

A. ValidB. Invalid, wrong number of arguments,C. Invalid, wrong type of arguments.

Page 63: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

guess what… the println method is overloaded!

63

println(String s) {…}println(int i) {…}println(double d) {…}println(char c) {…}…

System.out.println(total);

System.out.println("The total is:");…

Page 64: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

practical when the same operation must be done on different types or different numbers of parameters

64

public class Calculator{ public int addem(int op1, int op2) { return op1+op2; } public int addem(int op1, int op2, int op3) { return op1+op2+op3; }

public int opposite(int op) { return -op; } public boolean opposite(boolean op) { return !op; } public char opposite(char op) { if (Character.isUpperCase(op)) return Character.toLowerCase(op); return Character.toUpperCase(op); }}

Calculator myCalc = new Calculator();

System.out.print(myCalc.addem(10,20));

System.out.print(myCalc.addem(10,2,5));

System.out.print(myCalc.opposite(10));

System.out.print(myCalc.opposite('a'=='b'));

System.out.print(myCalc.opposite('a'));

Calculator.java

driver

Page 65: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

Constructors are methods… so they can be overloaded

65

public class Account{ private long acctNumber; private double balance; private String name;

public Account(String owner, long nb, double init) { name = owner; acctNumber = nb; balance = init; } public Account(String owner, long nb) { name = owner; acctNumber = nb; balance = 0; } public Account(long nb) { name = ""; acctNumber = nb; balance = 0; }…

public class Banking{ public static void main (String[] args) { Account acct1 = new Account("Jane", 456, 400); // 1. ok? Account acct2 = new Account("Ted", 123); // 2. ok? Account acct3 = new Account("Ted"); // 3. ok? Account acct4 = new Account(); // 4. ok? }}

Banking.javaAccount.java

Page 66: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

Information hiding separating how to use a class from how it is implemented Abstraction is another term used

Encapsulation the data and methods of a class are combined into a single

unit (i.e., a class object), which hides the implementation details

Knowing the details is unnecessary because interaction with the object occurs via a well-defined and simple interface

In Java, hiding details is done by marking them private

Interface an object interacts with the rest of the program via an

interface interface = set of methods that allow access to the object the interface hides how a method is implemented

66

Page 67: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

An encapsulated object can be thought of as a black box its inner workings are hidden to the client the client can access the object only by invoking the methods

of the interface

67

Client Public Methods

Data

(Interface)Private Methods

Page 68: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

Java has 4 visibility modifiers: public private protected (involves inheritance, see COMP 249) default or package (COMP 249)

can be applied to all members (data and methods)

68

Page 69: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

public members can be directly accessed from anywhere (inside &

outside the object) violate encapsulation

private members can only be accessed from inside the class definition

by default… members can be accessed by any class in the same

package i.e. access is more open than private, but more strict

than public

69

Page 70: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

Data: should be private public data violate encapsulation constants are OK to be public because they cannot be

modified anyways

Methods: should be public

if the method provides the object's services so that it can be invoked by clients also called service method

should be private if the method is created simply to assist a service method also called a support method

70

Page 71: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

71

public private

Variables

Methods

NO!Violates

encapsulation

YES!Enforces

encapsulation

Yes, if methodprovides services

to clients

Yes, if methodsupports othermethods in the

class

Page 72: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

public class Account { private double rate; private long acctNumber; private double balance; private String name;

public Account(String owner, long nb, double init) {

name = owner; acctNumber = nb; // 1. OK ? balance = init; rate = 0.02; } public double deposit(double amount) { if (amount < 0) // deposit is negative System.out.println("Error"); else balance += amount; //2.OK ? return balance; } private void changeRate(double newRate) {

rate = newRate; }…

72

public class Banking{ public static void main (String[] args) { Account acct1; double tedBal;

acct1 = new Account("Ted", 72, 102.56);

acct1.deposit(25.85); // 3. OK ?

acct1.balance = 0; // 4. OK ?

tedBal = acct1.deposit(500.00); //5.OK? acct1.changeRate(5.5); // 6. OK? }}

Account.java driver

Page 73: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

public class Printer{ private final int DEFAULT_NB = 10; public void printMany(int nbTimes, String theMessage) {

if (nbTimes < 0 || nbTimes > 100)internalUseOnly(DEFAULT_NB, theMessage);

else internalUseOnly(nbTimes, theMessage); }

private void internalUseOnly(int nbTimes, String AMess) {

for (int i = 1; i <= nbTimes; i++) System.out.println(AMess); }}

73

public class PrinterDriver{ public static void main (String[] args) { Printer myPrinter = new Printer();

myPrinter.printMany(5, "hello"); // 1. ok? System.out.println(myPrinter.DEFAULT_NB); // 2. ok? myPrinter.internalUseOnly(5, "hello"); // 3. ok? }}

class def.

driver

Page 74: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

data members are usually private so to access them, we usually have set and get methods

mutator (setX): sets the data X and makes sure it stays in a coherent state

accessor (getX): returns the value of data X

74

public class Time { private int hour; private int minutes; private int seconds;

public void setHour(_____________) { ________________________________;

}

public void setMinute(___________) { ______________________________;

}

public void setSecond(___________) { _______________________________

}

public int getHour(_______________) {_______________;

} public int getMinute(_______________){

_______________; } public int getSecond(_______________){

_______________; } // constructor public Time(int h, int m, int s) {

________________________;________________________;________________________;

}}

why should the set and get methods be public?

Page 75: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

if a mutator is given a value that would make the object in an invalid state, it can:

1. display an error message, and quit the program, OR2. return a boolean (false), and let the calling method

decide what to do

75

public setHour(int newHour) {

}

public void setHour(int newHour) {

if (newHour > 24 || newHour < 0){ System.out.println("Error.");

System.exit(0); } else hour = newHour;}

Page 76: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

an object can be a parameter to a method ex:

76

public void printMany(int nbTimes, String AMess) {…}

public int compareTo(String AMess) {…}

String originalString = "hello";int result = originalString.compareTo("bye bye");

String class

MyPrinters class

MyPrinter p = new MyPrinter();p.printMany(10, "hello");

Page 77: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

77

public class Time { private int hour; private int minutes; private int seconds;

public Time(int h, int m, int s) {…} public void setHour(int h) {…} … public int getSecond(){…}

// method to check if a time < another time

________________________________________

{

if (hour < anotherTime.getHour())

return true;

else if (hour > anotherTime.getHour())

return false;

else if (minutes < anotherTime.getMinute())

return true;

else if (minutes > anotherTime.getMinute())

return false;

return (seconds < anotherTime.getSecond());

}

public class TimeDriver{ public static void main (String[] args) {

// declare 2 time objects ________________________________;

________________________________;

// check if time1 < time2 if (_________________________________)

System.out.println("ok"); }}

Time.java

driver

Page 78: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

an object can be returned by a method ex:

78

public String toString() {…}

public String replace(char oldChar, char newChar) {…}

String myString = "hello";String newString = myString.replace('l', 'm');

String class

MyPrinters class

MyPrinters p = new MyPrinters();System.out.print(p.toString()); System.out.print(p);

Page 79: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

79

public class Time { private int hour; private int minutes; private int seconds;

// add a time to the current time

public ____________ add(________________)

{

Time result = new Time(0,0,0);

    result.hour = hour + t2.getHour(); result.minute = minutes + t2.getMinute(); result.second = seconds + t2.getSecond(); if (result.second >= 60) {       result.second -= 60;       result.minute += 1; } if (result.minute >= 60) {       result.minute -= 60;       result.hour += 1; } return result;

}

public class TimeDriver{ public static void main (String[] args) { Time t1 = new Time(9,10,50); Time t2 = new Time(19,5,5); Time t3 = new Time(0,0,0);

// t3 is the sum of t1 and t2

_______________________________ ; }}

Time.java

driver

Page 80: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

to define a class: data members (attributes)

declared outside any method must decide:

visibility (private? public?)

methods must decide:

visibility (private? public?) type of result (void?, int?, boolean?…) number and types of parameters actual code of the method static or not? (so far… never static)

2 files: the class definition (ex. Coin.java, BankAccount.java) the driver program (ex. CoinFlip.java, Banking.java)

80

Page 81: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

A set method is:

A. an accessor methodB. a mutator methodC. a recursive methodD. none of the above

81

Page 82: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

Accessor methods:

A. return something equivalent to the value of an instance variable.

B. promotes abstractionC. both A and BD. none of the above

82

Page 83: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

The parameter this refers to

A. instance variablesB. local variablesC. global variablesD. the calling object

83

Page 84: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

The name of a method and the list of ________ types in the heading of the method definition is called the method signature.

A. parameterB. argumentC. returnD. primitive

84

Page 85: Chapter 4: Defining Classes 1 1. 1.Writing our own classes 1.1 Instance Variables 1.2 Methods 2.Some notions of OOP 3.Passing and returning objects 4.Recap

85

name type visibility public class Rational { // data members:

numerator

denominatorname return

typeparameters

visibility

// methods headers

Rational {…}

getNumer {…}

setNumer {…}

reciprocal {…}

add {…}

toString {…}

reduce {…}

}