Class Object
Class Object
1
Contents
Arrays
Parameter Passing
TWO PARADIGMS IN OOP
All computer programs consist of two elements:
⚫ code and data.
A program can be conceptually organized around its
code or around its data.
That is, some programs are written around “what is
happening” and others are written around “who is
being affected.”
These are the two paradigms that govern how an
O O P program is constructed.
In Procedural language data and operation/code
are separate
Example (using C)
⚫ Student – 4 fields: name, id, cgpa, creditCompleted
⚫ Update cgpa – need a function to calculate the new cgpa
CLASS & OBJECT
Object
⚫ An object is a software bundle of related state and
behavior.
⚫ Software objects are often used to model the real-
world objects that you find in everyday life.
Class
⚫ A class is a blueprint or prototype from which
objects are created.
⚫ It defines what should be in each object and how
each object should behave.
WHAT IS CLASS
the class is the basis for object-oriented
programming in Java.
it defines a new data type.
from
the data for another.
⚫ Methods(action/behavior)
The code is contained within methods
In most classes, the instance variables are acted upon and
retyrntype
methodname1(parameter-
list) {
// body of method
}
returntype
methodname2(parameter-
list) {
// body of method
}
// ...
returntype
A SIMPLE CLASS
public class BankAccount {
// Instance variables
public String name;
public String id;
public double balance;
// Methods
public void
deposit(double
amount){
balance = balance +
amount;
}
⚫Calling methods
refVariable.methodName(parameter-list);
CREATE OBJECT AND
ACCESS MEMBERS
public class TestBankAccount {
public static void main(String[] args) {
// C reating objects
BankAccount account = new BankAccount();
// Assigning values to instance variables
account.name = "Rashid";
account.id = “1000500”;
account.balance = 1000;
// Print balance
System.out.println(“Balance before deposit: " + account.balance);
// C alling methods
account.deposit(2000);
// Print balance
System.out.println(“Balance after deposit: " + account.balance);
}
}
Output:
Balance before deposit: 1000.0
Balance after deposit: 3000.0
CREATE OBJECT AND
ACCESS MEMBERS
public class TestBankAccount {
public static void main(String[] args) { Use “new”
// C reating
BankAccount account = new BankAccount(); keyword to
objects
create object
// Assigning values to instance
account.name
variables = "Rashid"; Use “dot operator” (.) to
account.id = “1000500”;
account.balance = 1000; access
attributes and methods.
// Print balance
System.out.println(“Balance before deposit: " + account.balance);
// C alling methods
account.deposit(2000);
// Print balance
System.out.println(“Balance after deposit: " + account.balance);
}
}
Output:
Balance before deposit: 1000.0
Balance after deposit: 3000.0
REFERENCE VARIABLE
BankAccount account; accoun
t
account.name = “Rashid”;
account.id = “1000500”;
account.balance = 1000;
name = Rashid
accoun reference
t id = 1000500
balance = 1000
CREATE OBJECT AND
ACCESS MEMBERS
public class TestBankAccount {
public static void main(String[] args) {
// C reating objects
BankAccount accountR = new BankAccount();
BankAccount accountK = new BankAccount();
// Assigning values to instance
variables accountR.name = "Rashid";
accountR.balance = 1000;
accountK.name = "Kashem";
accountK.balance = 1000;
// C alling methods
accountK.deposit(2000);
// Print balance of both
account
System.out.println("Kashe
m's balance: " +
accountK.balance);
System.out.println("Rashi
d's balance: " +
accountR.balance);
}
}
Output:
REFERENCE VARIABLE
Before deposit
name = Rashid
account reference
R id = null
balance = 1000.0
name = Kashem
account reference
K id = null
balance = 1000.0
After deposit:
name = Rashid
account reference
R id = null
balance = 1000.0
name = Kashem
account reference
K id = null
balance = 3000.0
INITIALIZING
FIELDS/INSTANCE
VARIABLES
INITIALIZING FIELDS
There are three ways in Java to give a field an
initial value:
⚫ Direct Assignment
⚫ Instance Initialization Block
⚫ Constructors
1.DIRECT ASSIGNMENT
public class BankAccount {
// Instance variables
public String name;
public String id;
public double
balance = 100.0; //
direct assignment
// Methods
public void
deposit(double
amount){
balance = balance +
amount;
}
// M ethods
public void
deposit(double
amount){
balance = balance +
amount;
}
public void withdraw(double amount){
if (amount<balance)
balance -= amount;
}
// Constructor without
parameter
public BankAccount(){
id = new
Random().nextInt(9
9999) + "";
// name and
balance will get
default value
}
// Constructor with
parameter
public
BankAccount(String
_name, String _id,
double _balance){
name = _name;
3.DEFAULT CONSTRUCTOR
When you do not explicitly define a constructor for a class,
⚫ then J ava creates a default constructor for the class.
⚫ This is why the first BankAccount class code worked
even though that did not define a constructor.
// Constructor without
parameter
public BankAccount(){
id = new
Random().nextInt(9
9999) + "";
// name and
balance will get
default value
}
// Constructor with
parameter
public
BankAccount(String
_name, String _id,
double _balance){
name = _name;
CONSTRUCTOR - EXAMPLE
import java.util.Random;
public class BankAccount {
// Instance variables
public String name;
public String id;
public double balance;
// Constructor without
parameter
public BankAccount(){
id = new
Random().nextInt(9
9999) + "";
// name and
balance will get
default value
}
// Constructor with
parameter
public
BankAccount(String
name, String id,
double balance){
name = name;
CONSTRUCTOR - EXAMPLE
import java.util.Random;
public class BankAccount {
// Instance variables
public String name;
public String id;
public double balance;
// Constructor without
parameter
public BankAccount(){
id = new
Random().nextInt(9
9999) + "";
// name and
balance will get
default value
}
// Constructor with
parameter
public BankAccount(String name, String id, double balance)
{ this.name = name;
this.id = id;
this.balance = balance;
}
SCOPE & LIFETIME
OF VARIABLES
SCOPE OF VARIABLE
What is scope?
⚫ A scope determines what variable are visible to other parts of
your program. Or where the variable is accessible?
⚫ It also determines the lifetime of those variable.
A block defines a scope.
⚫ the statements between opening and closing curly braces.
As a general rule, variables declared inside a scope are
not visible (that is, accessible) to code that is defined
outside that scope.
Within a block, variables can be declared at any point, but
are valid only after they are declared.
⚫ Thus, if you define a variable at the start of a method, it is
available to all of the code within that method.
⚫ Conversely, if you declare a variable at the end of a block, it is
effectively useless, because no code will have access to it.
SCOPE OF VARIABLE -
EXAMPLE
public void calculateInterest(double balance)
{
if(balance > 10000)
{
float interest = 0.05f; // Scope of this variable is only inside the if
block
}
else
{
interest = 0.02f; // compiler error. interest is declared inside the if
block, hence can't access in else block
}
}
To make “interest” accessible to both if and else block it
has to be declared outside of the block.
SCOPE OF VARIABLE -
EXAMPLE
public void calculateInterest(double balance)
{
float interest; // accessible to anywhere inside the method.
if(balance > 10000)
{
interest = 0.05f; // Ok
}
else
{
interest = 0.02f; // O K
}
}
SCOPE OF VARIABLE
Many other computer languages define two general
categories of scopes:
⚫ global and local.
However, these traditional scopes do not fit well with
Java’s strict, object-oriented model.
In Java, the two major scopes are
⚫ those defined by a class and
⚫ those defined by a method.
WHEN CAN 2 VARIABLES
HAVE SAME NAME
Instance variable and Local variable.
Local variable in 2 different methods.
2 Local variables in the same methods but only after the
death of one Local variable.
OK Wrong
public void public void
calculateInterest(double balance) { calculateInterest(double balance) {
if(balance > 10000){ float interest;
float interest = 0.05f; // OK if(balance > 10000){
} float interest =
else { 0.05f; // Compiler
float interest = 0.02f; // OK error
} }
} else {
interest = 0.02f; //
OK
}
}
ARRAYS
ARRAY AGAIN
name = Rashid
stude reference id =
nt
011153001
cgpa= 3.0f
creaditComplet
ed = 50
What value will you get when you access the following
attributes of student reference variable/object.
⚫ student.name
⚫ student.id
⚫ student.cgpa
⚫ student.creditCompleted
REFERENCE TYPE WITH
NULL
Student student = null;
stude null
nt
What value will you get when you access the following
attributes of student reference variable/object.
⚫ student.name
⚫ student.id
⚫ student.cgpa
⚫ student.creditCompleted
REFERENCE TYPE WITH
NULL
We cant access any member via the reference
variable when no object is created.
Accessing the member will throw
NullPointerException.
REFERENCE TYPE ARRAY
Example
Student[] students = new Student[3];
System.out.println(students[0].cgpa); // What would be
the output of this line.
null
student reference
s null
null
REFERENCE TYPE ARRAY
Need to initialize the element before accessing.
Example
Student[] students = new Student[3];
students[0] = new Student(“Rashid”, “011153001”, 3.0f, 50);
students[1] = new Student(“Zaman”, “011153021”, 3.0f, 50);
students[2] = new Student(“Lubna”, “011153031”, 3.5f, 50);
System.out.println(students[0].cgpa); // What would be the
output of this line.
name = Rashid
id =
011153001
Ref cgpa= 3.0f
creaditCompleted = 50
name = Zaman
student reference id =
s Ref
011153021
name = Lubna cgpa= 3.0f
Ref id = 011153031 creaditComplet
cgpa= 3.5f ed = 50
creaditCompleted = 50
PARAMETER PASSING
PARAMETER PASSING
2 different ways
⚫ Pass By Value
⚫ Pass By Reference
C , C++, php
main() {
int i = 10, j = 20;
cout << i << " " << j << endl;
swapThemByRef(i, j);
cout << i << " " << j << endl;
} // displays 20 10 ...
Output:
void swapThemByRef(int& num1, int& num2) {
10 20
int temp = num1; 20 10
num1 = num2;
num2 = temp;
}
PASS BY REFERENCE
At the beginning of function call
i 10 20
j
num num tem
1 2 p
Example:
main() { Output:
int i = 10, j = 20; 10 20
cout << i << " " << j << endl; 10 20
swapThemByVal(i, j);
cout << i << " " << j << endl;
// displays 20 10 ...
}
void swapThemByVal(int num1, int num2) {
int temp = num1;
num1 = num2;
num2 = temp;
}
PASS BY VALUE
At the beginning of method call
i 10 20
j
num 10 20 num tem
1 2 p
pass-by-reference.
Why?
void display(){
System.out.printf("TestName: %s ; Score: %.2f \n", testName,
score);
}
}
PASS BY VALUE – WITH
OBJECT
public class PassByValue {
public static void main(String[] args) {
Test t = new Test("CT1", 10);
t.display();
updateScore(t, 15.0f );
System.out.println("After Update:");
t.display();
}
Output:
TestName: CT1 ; Score: 10.00
After Update:
TestName: CT1 ; Score: 15.00
PASS BY VALUE – WITH
OBJECT
t Objec
t
Before the method call reference testName= “CT1”
score = 10.0f;
Heap
Stack
name = Rashid
id = 1000500
balance = 1000.0
account reference
R
name = Kashem
account reference
K id = 1000501
balance = 10000.0
GARBAGE COLLECTION –
SCENARIO#1
BankAccount accountR = new BankAccount(“Rashid”, “1000500” , 1000.0);
BankAccount accountK = new BankAccount(“Kashem”, “1000501” , 10000.0);
accountR = accountK;
// Rashid’s object can no longer be accessed and is
eligible for garbage collection
Heap
name = Rashid
id = 1000500
Stack
balance = 1000.0
account reference
R
name = Kashem
account reference
K id = 1000501
balance = 10000.0
GARBAGE COLLECTION –
SCENARIO#2
BankAccount accountR = new BankAccount(“Rashid”, “1000500” , 1000.0);
Heap
name = Rashid
id = 1000500
balance = 1000.0
Stack
account reference
R
name = Kashem
account reference
K id = 1000501
balance = 10000.0
GARBAGE COLLECTION
– SCENARIO#2
BankAccount accountR = new BankAccount(“Rashid”, “1000500” , 1000.0);
BankAccount accountK = new BankAccount(“Kashem”, “1000501” , 10000.0);
accountR = null;
// Rashid’s object can no longer be accessed and is eligible for garbage collection
Heap
name = Rashid
id = 1000500
account null
R
name = Kashem
account reference
K id = 1000501
balance = 10000.0
GARBAGE COLLECTION –
SCENARIO#3
public class TestMain{
public static void main(String[] args) {
updateScore(new Test("CT1", 10), 15.0f );
}
public class
Test{ String
testName; float
score;
testName= “CT1”
score = 15.0f; Hea
p
PACKA
GE
WHAT IS PACKAGE?
Packages are used to group related classes.
A package is a namespace that organizes a set of
name.
Class1
Package2 C lass2
Package2_2 C la ss1
Package1
C la ss1
Package3
C lass1 Not
Allowed
WHAT IS PACKAGE?
Classes in same package can not have duplicate
name.
Classes in different packages can have the same
name.
Class1
Package2 C lass2
Package2_2 C la ss1
Package1
C la ss1
Package3
Class3
HOW TO CREATE
PACKAGE?
To create a package is quite easy:
⚫ simply include a package command as the first
statement in a J ava source file.
package pkg;
⚫ Any classes declared within that file will belong to
the specified package.
⚫ J ava uses file system directories to store
packages.
You can create a hierarchy of packages.
⚫ Use period/dot to separate each package name
from
the one above it.
package pkg1.pkg2.pkg3;
PACKAGE -
EXAMPLE
Example:
package uiu.cse;
public class Test{
public void
display() {
System.out.p
rintln( "Hell
o for Test
class." );
}
}
1. The class
must be in a
file named
“Test.java"
2. Place the file
PACKAGE -EXAMPLE
If you use I DE ,
⚫ 1-3 will be done automatically and “cse” will be
placed under the “src” folder.
⚫ If no package is specified the file will be placed in a
default package which maps to “src” folder
BENEFITS OF USING
PACKAGE
The package is both a naming and a
visibility control mechanism.
Packages are important for three main
reasons.
⚫ First,they help the overall organization of a
project or library.
Can organize code in a logical manner
makes large software projects easier to manage
BENEFITS OF USING
PACKAGE
Second, packages give you a name scoping, to
help prevent collisions.
⚫ What will happen if you and 12 other programmers
in your company all decide to make a class with the
same name.
⚫ public
⚫ Protected
⚫ Default/Package Access – No modifier
⚫ Private
Outer class can only be declared as public or
default.
PRIVATE
Members declared private are accessible only in
the class itself
Example:
class Private {
private String name = "Private";
public void print()
{ System.out.println( name
);
}
}
class PrivateExample {
public static void main( String[] args ) {
Private pr = new Private();
pr.print(); // O K
System.out.println( pr.name ); //
Compile error
}
DEFAULT/PACKAGE
ACCESS
the class.
⚫ Not even child class.
DEFAULT/PACKAGE
ACCESS - EXAMPLE
Class that will be accessed from other classes
package test;
class Default{
String
name =
“Default“;
}
Class under
different
package
package
test1;
class
DefaultExam
ple {
public static void main( String[] args ) {
Default dfl= new Default();
System.out.println( dfl.name ); //
Compile error
}
}
DEFAULT/PACKAGE
ACCESS - EXAMPLE
Child Class under different package
package test1;
class DefaultChild extends Default {
public DefaultChild() {
name = “Child”; // Compile error
}
}
Class Under
Different
Package
package test1;
class
ProtectedExamp
le {
public static void main( String[] args ) {
Protected pr = new Protected();
System.out.println( pr.name ); //
Compile error
}}
PROTECTED -
EXAMPLE
Child Class Under Different Package
package test1;
class ProtectedChild extends Protected {
public ProtectedChild() {
pr.name = “Child”; // O K
}
}