Title: More about classes
1More about classes
syllabus
- Defining classes revisited
- Constructors
- Defining methods and passing parameters
- Visibility modifiers and encapsulation revisited
basic programming concepts
object oriented programming
topics in computer science
2Objects 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 data - ChessPiece 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
3Designing a class the class abstraction
Clock(int hours, int minutes, int seconds)
void secondElapsed()
int getSeconds()
int getMinutes()
int getHours()
...
- // 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
-
- // ...
4Method Declarations Revisited
- A method declaration begins with a method header
String seeTime (int hours, int minutes, int
seconds)
method name
parameter list
The parameter list specifies the type and name of
each parameter The name of a parameter in the
method declaration is called a formal argument
return type
5Method 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
result is local data It is created each time the
method is called, and is destroyed when it
finishes executing
The return expression must be consistent with the
return type
6Constructors
- 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
7Constructors
- // 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 000000
- public Clock()
- hours 0
- minutes 0
- seconds 0
-
8Constructors
- The statement new Clock() does the following
9Constructors
- The statement new Clock() does the following
- 1) Allocates the memory for a new clock object
clock hours minutes seconds
10Constructors
- The statement new Clock() does the following
- 1) Allocates the memory for a new clock object
- 2) Initializes its state by calling the
constructor
clock hours 0 minutes 0 seconds 0
11Constructors 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
12Methods
- 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
13Modifiers 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
14Return 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
15Method 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
16- 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
-
17The this 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
-
18Method 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)
19- 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. - // _at_param hours the hours to be set (0-23)
- // _at_param minutes the minutes to be set (0-59)
- // _at_param seconds the seconds to be set (0-59)
-
- public void setTime(int hours, int minutes, int
seconds) -
- if ((seconds 0) (seconds
- (minutes 0) (minutes
- (hours 0) (hours
- this.hours hours
- this.minutes minutes
- this.seconds seconds
-
20Example a Student Object
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
Student Rachel Rachel new Student(123456789,
math) Rachel.changeMaslul(computer science)
21Passing parameters
- Each time a method is called, the actual
arguments in the invocation are copied into the
formal arguments
time obj.seeTime (20, 30, 40)
return 203040
22Example 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)
23Writing 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
24// A bank account public 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
25 // 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(am
ount) --------------------------------------
--------------------- BankAccount tomAccount
new BankAccount(1398723,Tom) BankAccount
shirAccount new BankAccount(1978394,Shir) tom
Account.deposit(500) // Toms balance
500 tomAccount.transfer(700,shirAccount) //
Toms balance -200, Shirs balance 700
26Encapsulation not Among Instances of Same Class
- Sometimes object instances of the same class need
to access each others 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) -
27Passing 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