0% found this document useful (0 votes)
33 views

CS 241 Lec 7 - 2

The document discusses the this keyword in Java and how it can be used to refer to current class instance variables, invoke current class constructors, and resolve ambiguity between local variables and instance variables. It also provides an example of designing an Account class with variables, constructors, and methods for depositing, withdrawing, and retrieving account information.

Uploaded by

Essam El-Uddaly
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
33 views

CS 241 Lec 7 - 2

The document discusses the this keyword in Java and how it can be used to refer to current class instance variables, invoke current class constructors, and resolve ambiguity between local variables and instance variables. It also provides an example of designing an Account class with variables, constructors, and methods for depositing, withdrawing, and retrieving account information.

Uploaded by

Essam El-Uddaly
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

1

CS 241: OBJECT
ORIENTED
PROGRAMMING
Dr. Ibrahim Eldesoky
[email protected]
2

This Keyword in Java


• There are many usages fro the word this in Java, here is
some of them:
• this keyword can be used to refer current class instance variable.
• this() can be used to invoke current class constructor.
• this keyword can be used to invoke current class method (implicitly)
3

This Keyword in Java


4

This Keyword in Java


• (1) The this keyword can be used to refer current
class instance variable.
• If there is ambiguity between the instance variable and
parameter, this keyword resolves the problem of
ambiguity.
5

This Keyword in Java


• Understanding the problem without this keyword
class Student10{
int id; String name;
student(int id,String name){
id = id; name = name; }
void display(){
System.out.println(id+" "+name);}
public static void main(String args[]){
Student10 s1 = new Student10(111,"Karan");
Student10 s2 = new Student10(321,"Aryan");
s1.display();
s2.display();
} }
• //output 0 null
0 null
6

This Keyword in Java

Solution of the above problem by this keyword

In the above example, parameter (formal arguments) and instance variables


are same that is why we are using this keyword to distinguish between local
variable and instance variable.
7

This Keyword in Java


class Student10{
int id; String name;
student(int id,String name){
this.id = id; this.name = name; }
void display(){
System.out.println(id+" "+name);}
public static void main(String args[]){
Student10 s1 = new Student10(111,"Karan");
Student10 s2 = new Student10(321,"Aryan");
s1.display();
s2.display();
} }
// Output 111 Karan
222 Aryan
8

This Keyword in Java

• If local variables(formal arguments) and instance variables are


different, there is no need to use this keyword
9

This Keyword in Java


• (2) this() can be used to invoked current class
constructor.
• The this() constructor call can be used to invoke the
current class constructor (constructor chaining). This
approach is better if you have many constructors in the
class and want to reuse that constructor.
10

This Keyword in Java


class Student13{
int id; String name;
Student13(){
System.out.println("default constructor is invoked");}
Student13(int id,String name){
this ();//it is used to invoked current class constructor.
this.id = id; this.name = name; }
void display(){
System.out.println(id+" "+name);}
public static void main(String args[]){
Student13 e1 = new Student13(111,"karan");
Student13 e2 = new Student13(222,"Aryan");
e1.display();
e2.display();
} }
//Output: default constructor is invoked
default constructor is invoked
111 Karan
222 Aryan
11

This Keyword in Java


Where to use this() constructor call?

The this() constructor call should be used to reuse the constructor in the
constructor. It maintains the chain between the constructors i.e. it is used for
constructor chaining. Let's see the example given below that displays the actual
use of this keyword.
12

This Keyword in Java


class Student14{
int id; String name; String city;
Student14(int id,String name){
this.id = id; this.name = name; }
Student14(int id,String name,String city){
this(id,name); //now no need to initialize id and name
this.city=city; }
void display(){
System.out.println(id+" "+name+" "+city);}
public static void main(String args[]){
Student14 e1 = new Student14(111,"karan");
Student14 e2 = new Student14(222,"Aryan","delhi");
e1.display();
e2.display();
} }
Output:111 Karan null
222 Aryan delhi
Note: Call to this() must be the first statement in constructor.
13

This Keyword in Java (Shadowing)

public class T {
int x; // an instance variable
void m1( int x) { ... }
// x is shadowed by a parameter
void m2() { int x; ... }
} // x is shadowed by a local variable

• To be able to access a shadowed instance variable, within


methods m1 or m2 you have to use this keyword (this.x).

Void m1 (int x) {
this.x = x;
// assign the value of the parameter x to the instance variable x
}
14

An Example – Designing A Class

• The following few pages will present a


complete example of designing a class from
the ground up for a specific application.
• Our application is a banking enterprise where
we need to keep track of customer accounts.
• We will design a class called Account.
15

Design of the class Account

•Variables to describe the state of an Account object:


name of the owner
account number
balance in the account
•Data we are going to provide to create a new account
name of the owner
opening balance
account number
•Methods (services) provided for maintaining accounts
deposit an amount
withdraw an amount
get name of the owner
get balance
16

public class Account{

private long acctNumber;


private double balance;
private String name;

//---------------------------------------------------
// Sets up the account by defining its owner,
// account number, and initial balance.
//---------------------------------------------------

public Account(String name, long acctNumber,


double balance)
{
this.name = name;
this.acctNumber = acctNumber;
this.balance = balance;
}
17
//-------------------------------------------------
// Validates the transaction, then deposits
// the specified amount into the account.
//-------------------------------------------------

Public deposit (double amount) {


if (amount < 0) // deposit value is negative
{
System.out.println ();
System.out.println ("Error: Deposit amount
is invalid.");

}
else
balance = balance + amount;

}
18
public withdraw (double amount) {

if (amount < 0) // withdraw value is negative


{
System.out.println();
System.out.println ("Error: Withdraw amount is
invalid.");
}
else
if (amount > balance) // withdraw value exceeds balance
{
System.out.println ();
System.out.println ("Error: Insufficient funds.");
System.out.println ("Account: ” +acctNumber);
System.out.prin (“you Requested”+ amount);
System.out.prin (“ and the Available is “ +balance);
}
else
balance = balance - amount;
}
19

//accessors
public String getName () {
return name;
}

public double getBalance () {


return balance;
}

public long getAccountNumber () {


return acctNumber;
}

// overridden toString
public String toString () {
return acctNumber + "\t" + name +
"\t" + balance;
}
}// end class Account
20

The BankAccounts Class

public class BankAccounts {


//Creates some bank accounts and requests various services.

public static void main (String[] args) {


Account acct1=new Account(“Ahmed Mohammed",
72354, 502.56);

Account acct2=new Account(“Mostafa Ahmed",


69713, 40.00);

Account acct3=new Account(“Mohammed Ali",


93757, 759.32);
21

acct1.deposit (25.85);
acct2.deposit(500.00);

System.out.println (“balance after


deposit:” + acct2.getBalance());

System.out.println (“balance after


withdrawal: ” + acct2.withdraw(430.75));

System.out.println ();
System.out.println (acct1);
System.out.println (acct2);
System.out.println (acct3);
} // end of main
} // end of class BankAccount
22

Let’s take a closer look on methods invocation and the


rules of parameters passing in java

• Pass by reference
• Pass by value
23

Parameters passing

• The parameters in the method definition are called formal


parameters.
• Each parameter in the parameter list is specified by its type and
name.
• A method has zero or more parameters.

• When a method is invoked The values passed to it are called


actual parameters.
• The first actual parameter corresponds to the first formal
parameter, the second actual parameter to second formal
parameter, and so on..
• The type of each actual parameter must be identical to the
corresponding formal parameter.
24

Parameters passing (cont.)

ch = obj.calc (25, count, "Hello");

char calc (int num1, int num2, String message)


{
}
25

Parameters passing (cont.)


• When a method is invoked:

• Java sets aside activation record memory for that particular


invocation
• Activation record stores, among other things, the values of the
formal parameters and local variables

• Formal parameters initialized using the actual parameters


• After initialization, the actual parameters and formal
parameters are independent of each other

• Flow of control is transferred temporarily to that method


26

Parameters Passing – Call by value

• When the type of the formal parameter is a primitive


data type, the value of the actual parameter is passed
into the method and saved in the corresponding formal
parameter (CALL-BY-VALUE).

• If a method updates the value of a formal parameter, the


changes DOES NOT affect the actual parameter. The
change is limited to the activation record containing the
value of the formal parameter.

• In call-by-value, there is no way to change the value of


the corresponding actual parameter in the method.
27

Parameter Passing in Java – call by reference

• When the type of the formal parameter is an object data


type, the reference to an object is passed into the
method and this reference is saved in the corresponding
formal parameter (CALL-BY-REFERENCE).

• The actual and formal parameters are aliased variables.

• The object to which the actual parameter refers can


be modified in a method invocation.
28

Parameter passing - Call by value - Example


public class Demo {
//add() returns the sum of its parameters
public static double add(double x, double y){
double result= x+y;
return result; }

//multiply() returns the product of its parameters


public static double multiply(double x, double y){
x = x * y;
return x; }

//main() application entry point


public static void main(String[] args){
double a = 8;
double b = 11;

double sum = add(a, b);


System.out.println (a + " + " + b + " = " + sum);
double product = multiply(a, b);
System.out.println (a + " * " + b + " = " + product);
} }
29

Demo.java - Run

multiply() does not


change the actual
parameter a
30

Parameter Passing - Example1 (cont.)

Part of the activation record of main().

main()

a 8.0

b 11.0

sum -

product -
31

Demo.java - walkthrough

double sum = add(a, b);


Initial values of formal parameters
come from the actual parameters
public static double add(double x, double y) {
double result = x + y
return result;
}

main()
add()
a 8.0
x 8.0
b 11.0
y 11.0
sum -
result -
product -
32

Demo.java - walkthrough

public static double add (double x, double y){


double result= x+y;
return result;
}

main() add()

a 8.0 x 8.0

y 11.0
b 11.0
result 19.0
sum 19.0

product -
33

Demo.java walkthrough

double multiply = multiply(a, b);


Initial values of formal parameters
come from the actual parameters
public static double multiply(double x, double y) {
x=x*y
return x;
}

main() multiply()

a 8.0 x 8.0

b 11.0 y 11.0

sum 19.0

product -
34

Demo.java walkthrough

public static double multiply(double x, double y) {


x = x * y;
return x;
}

main()
multiply()
a 8.0
x 88.0
b 11.0
y 11.0

sum 19.0

product -
35

Demo.java - walkthrough

public static double multiply(double x, double y) {


x = x * y;
return x;
}

main()
multiply()

a 8.0 x 88.0

b 11.0 y 11.0

sum 19.0

product 88.0
36
Point Class

• It’s a class in java.awt


• It’s used to represent a point in two dimensional space

• It has two instance variables:


• int x, int y;

• One of its constructors is :

• Public Point (int a, int b)


Constructs new point representing the location (a,b)

• One of its instance methods is:

• setLocation (int a, int b);


Reset the point to represent the location a,b
37

Parameter Passing – call by reference - Example


import java.awt.*;
public class PassingReferences {

public static void f(Point v){


v = new Point(0,0); }

public static void g(Point v){


v.setLocation(0,0); }

public static void main(String[] args){

Point p = new Point(10,10);


System.out.println(p);
f(p);
System.out.println(p);
g(p);
System.out.println(p);
}}
38

PassingReferences.java - run

g() changed the attributes


of the object to which p
refers
39

PassingReferences- WalkThrough

Point p = new Point(10, 10);

main( )
Point
p
y: 10 x: 10

Notice that : Although variable p is part of the activation record for main(),
the memory for the Point object which it refers to is not part of the
activation record.
Java divides the memory allocated to a program into two parts – the stack
and the heap.
Activation records are maintained in the stack while objects in the heap.
40
PassingReferences- WalkThrough
•f(p) ; Method f() is invoked with p as the actual parameter.
•The invocation causes:
•the creation of an activation record for f ().
•The value of p is copied into the formal parameter v which is a
reference to a Point object (10,10). P and v refer the same object
•And the flow of control is passed to the method f.

main( )
Point
p
y: 10 x: 10

f( )

v
41
PassingReferences- WalkThrough

public static void f(Point v) { v = new Point(0,0); }


•The assignment statement in method f() is then executed, creating a new
Point object representing the location (0, 0). the references to this new
Point object is assigned to v. This assignment does not modify main() method
variable p because p and v are independent and each of them has its own
memory that stores its value.

main( ) Point

p
y: 10 x: 10

f( ) Point

v
y: 0 x: 0
42

PassingReferences- WalkThrough

•The activation record for f() is then released and flow of control
is transferred back to the main() method where a println
statement is executed.
•The activation record for main() looks like the following:

main( )
Point
p
y: 10 x: 10
43
PassingReferences- WalkThrough

g(p); Method g() is then invoked with p as the actual


parameter.
•v has the value of p which is a reference to a point object
representing location (10, 10).
•the flow of control is passed to the method p.

main( )
Point
p
y: 10 x: 10

g( )

v
44
PassingReferences- WalkThrough
public static void g (Point v) { v.setLocation(0,0); }
•Within method g() the Point instance method (v.setLocation(0,0)) is invoked on v. This
invocation causes an update to the Point object to which parameter v references. The update
changes (x,y) to (0, 0).
•Notice that this update changed neither actual parameter p nor formal parameter v.
However, the object to which they both refer has been updated and this update is visible
through either one of them (p & v are aliased).
•The activation records now look like those shown below:

main( )
Point
p
y: 0 x: 0

g( )

You might also like