Top Banner
1 unit 4II More about classes More about classes Defining classes revisited Constructors Defining methods and passing parameters Visibility modifiers and encapsulation revisited basic programmin g concepts object oriented programmin g topics in computer science syllabus
27

Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

Dec 19, 2015

Download

Documents

Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

1unit 4II

More about classesMore about classes

Defining classes revisited Constructors Defining methods and passing parameters Visibility modifiers and encapsulation

revisited

basic programming

concepts

object oriented programming

topics in computer science

syllabus

Page 2: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

2unit 4II

Objects and Pointers to objectsObjects and Pointers to objects

A class defines the characteristics associated with an object; when an object is created, it is allocated a block of memory sufficient to hold all its state variables

Variables of type object reference hold the memory address of the actual location of the dataChessPiece bishop1;

bishop1 = new ChessPiece(“bishop”,”b”,1);

The object reference variable and the object itself are separate entities; why?• when a variable of type object is defined, the size of the

memory block it will require is not known; on the other hand, a pointer is a primitive type

• we can treat all object references the same way

bishop1

Page 3: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

3unit 4II

Designing a class: the class abstractionDesigning a class: the class abstraction

// A clock representation class: clock instances// represent a point of time during the daypublic class Clock {

// The hours, minutes, and second read

private int hours, minutes, seconds;

// ...

}

Clock(int hours, int minutes, int seconds)

int getSeconds()

void secondElapsed()

int getMinutes()

int getHours()

...

Page 4: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

4unit 4II

Method Declarations RevisitedMethod Declarations Revisited

A method declaration begins with a method header

String seeTime (int hours, int minutes, int seconds)

methodmethodnamename

returnreturntypetype

parameter listparameter list

The parameter list specifies the typeThe parameter list specifies the typeand name of each parameterand name of each parameter

The name of a parameter in the methodThe name of a parameter in the methoddeclaration is called a declaration is called a formal argumentformal argument

Page 5: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

5unit 4II

Method DeclarationsMethod Declarations

The method header is followed by the method body

String seeTime (int hours, int minutes, int seconds)

{ String result = hours + `:` + minutes+

+ `:` seconds;

return result;}

The return expression must beThe return expression must beconsistent with the return typeconsistent with the return type

resultresult is is local datalocal data

It is created each time It is created each time the method is called, and the method is called, and is destroyed when it is destroyed when it finishes executingfinishes executing

Page 6: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

6unit 4II

ConstructorsConstructors

Objects must be initialized before they can be used: • We must specify the initial state of the object before

we can use it

• This is very similar to primitive data types: when we declare a new variable of type int, for example, we must give it an initial value

We specify the way an object is initialized using a constructor, which is a special method invoked every time we create a new object

Page 7: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

7unit 4II

ConstructorsConstructors

// A clock representation class; clock instances// represent a point of time during the day public class Clock {

// The hours, minutes, and second read private int hours, minutes, seconds;

// Constructs a new clock, sets the // clock to the time 00:00:00 public Clock() { hours = 0; minutes = 0; seconds = 0; }}

Page 8: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

8unit 4II

ConstructorsConstructors

The statement new Clock() does the following:

Page 9: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

9unit 4II

ConstructorsConstructors

The statement new Clock() does the following:

• 1) Allocates the memory for a new clock object

clock

hoursminutesseconds

Page 10: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

10unit 4II

clock

hours 0minutes 0seconds 0

ConstructorsConstructors

The statement new Clock() does the following:

• 1) Allocates the memory for a new clock object

• 2) Initializes its state by calling the constructor

Page 11: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

11unit 4II

Constructors RevisitedConstructors Revisited

When writing a constructor, remember that:• it has the same name as the class

• it does not return a value

• it has no return type, not even void• it often sets the initial values of instance variables

The programmer does not have to define a constructor for a class

Page 12: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

12unit 4II

MethodsMethods

To make the clock object useful, we must provide methods that define its behavior

Example:

// Advance the clock by one hour public void hourElapsed() { hours = (hours + 1) % 24; }

// Return the hour read public int getHours() { return hours; }

Page 13: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

13unit 4II

Modifiers of methodsModifiers of methods

The modifier public denotes that the methods hourElapsed() and getHour() are part of the interface of the class (the services that the class exposes to outside world clients)

The keyword void denotes that the method hourElapsed() has no return value

Page 14: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

14unit 4II

Return TypesReturn Types

The return type of a method indicates the type of value that the method sends back to the calling client

The return-type of getHours() is int; when a client asks for the hours read of a clock it gets the answer as an int value

A method that does not return a value (such as hourElapsed()) has a void return type

The return statement specifies the value that should be returned, which must conform with the return type of the method

Page 15: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

15unit 4II

Method ContextMethod Context

The getHours() and hourElapsed() methods are instance methods, which means they act on a particular instance of the class

They cannot be invoked “out of the blue”, but must act on a particular object:Clock c = new Clock();getHours(); // error: of which clock?c.getHours(); // will return 0

An instance method is executed in the context of the object it acts upon

Page 16: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

16unit 6

public class ClockTest {

public static void main(String[] args) { Clock swatch = new Clock(); Clock seiko = new Clock();

System.out.println(swatch.getHours()); // 0 System.out.println(seiko.getHours()); // 0

swatch.hourElapsed();

System.out.println(swatch.getHours()); // 1 System.out.println(seiko.getHours()); // 0 }}

Page 17: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

17unit 4II

The The thisthis Reference Reference

When appearing inside an instance method, the this keyword denotes a reference to the object that the method is acting upon

The following are equivalent: public int getHours() { return hours; } public int getHours() { return this.hours; }

Page 18: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

18unit 4II

Method ParametersMethod Parameters

A method can be defined to accept zero or more parameters; each

parameter in the parameter list is defined by its type and name

The parameters in the method definition are called formal

parameters; the values passed to a method when it is invoked are

called actual parameters

The name of the method together with the list of its formal

parameters is called the signature of the method

public void setTime(int hours, int minutes, int seconds)

Page 19: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

19unit 6

public class Clock { private int hours, minutes, seconds; // Sets the clock to the specified time. // If one of the parameters is not in the allowed // range, the call does not have any effect on the clock. // @param hours: the hours to be set (0-23) // @param minutes: the minutes to be set (0-59) // @param seconds: the seconds to be set (0-59) public void setTime(int hours, int minutes, int seconds) { if ((seconds >= 0) && (seconds < 60) && (minutes >= 0) && (minutes < 60) && (hours >= 0) && (hours < 24)) { this.hours = hours; this.minutes = minutes; this.seconds = seconds; } // no effect if input is illegal }}

Page 20: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

20unit 4II

public class student { private long ID; private String maslul;

// Constructor public student(long ID, String maslul) { this.ID =ID; this.maslul = maslul; }

// method: change maslul public void changeMaslul(String maslul) { this.maslul = maslul;

}

}

Example: a Student ObjectExample: a Student Object

Student Rachel;

Rachel = new Student(123456789, “math”);

Rachel.changeMaslul(“computer science”);

Page 21: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

21unit 4II

Passing parametersPassing parameters

Each time a method is called, the actual arguments in the invocation are copied into the formal arguments

String seeTime (int hours, int minutes, int seconds)

{ String result = hours + `:` + minutes+

+ `:` seconds;

return result;}

time = obj.seeTime (20, 30, 40);

return 20:30:40

Page 22: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

22unit 4II

Example: a Bank Account ObjectExample: a Bank Account Object

BankAccount

public BankAccount(long accountNumber, String owner)

public void deposit(float amount)

public void withdraw(float amount)

public void transfer

(float amount, BankAccount targetAccount)

Page 23: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

23unit 4II

Writing ClassesWriting Classes

An aggregate object is an object that contains references to other objects

A BankAccount object is an aggregate object because it contains a reference to a String object (that holds the owner's name)

An aggregate object represents a has-a relationship

A bank account has a owner

Page 24: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

24unit 6

// A bank accountpublic class BankAccount {

private long accountNumber; private float balance; // The balance in dollars private String owner;

// Constructs a new empty account public BankAccount(long accountNumber, String name) { this.accountNumber = accountNumber;

this.owner = name; this.balance = 0; }

// Deposites a given amount into the account

public void deposit(float amount) {

// ... perhaps perform some security checks

balance = balance + amount;

}

Page 25: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

25unit 6

// Withdraws a given amount from the account

public void withdraw(float amount) {

// ... perhaps perform some security checks

balance = balance - amount;

}

// Transfers a given amount into another bank account

public void transfer(float amount, BankAccount targetAcc)

{

// ... perhaps perform some security checks

this.withdraw(amount);

targetAcc.deposit(amount);

}

-----------------------------------------------------------

BankAccount tomAccount = new BankAccount(1398723,”Tom”);

BankAccount shirAccount = new BankAccount(1978394,”Shir”);

tomAccount.deposit(500); // Tom’s balance = 500

tomAccount.transfer(700,shirAccount);

// Tom’s balance = -200, Shir’s balance = 700

Page 26: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

26unit 4II

Encapsulation not Among Instances of Encapsulation not Among Instances of Same ClassSame Class

Sometimes object instances of the same class need to access each other’s “guts” (e.g., for state copying - if we want to create an identical instance of an object we have)

Example: from within a BankAccount object, any private member of a different BankAccount object can be accessed

public void transfer(float amount, BankAccount targetAcc) {

// ... perhaps perform some security checks

this.withdraw(amount);

targetAcc.balance += amount; // not: targetAcc.deposit(amount)

}

Page 27: Unit 4II 1 More about classes H Defining classes revisited H Constructors H Defining methods and passing parameters H Visibility modifiers and encapsulation.

27unit 4II

Passing Objects to MethodsPassing Objects to Methods

Parameters in a Java method are passed by value: a copy of the actual parameter (the value passed in) is stored into the formal parameter (in the method header)

Passing parameters is essentially an assignment

Both primitive types and object references can be passed as parameters

When an object is passed to a method, the actual parameter and the formal parameter become aliases