Lecture3 ClassObject
Lecture3 ClassObject
Tanjina Helaly
CONTENT
Class & Object.
Initializing Fields/Instance variables.
Arrays
Parameter Passing
Garbage Collection
Package
Access Modifier
Recursion
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.
retyrntype methodname1(parameter-list) {
// body of method
}
returntype methodname2(parameter-list) {
// body of method
}
// ...
returntype methodnameN(parameter-list) {
// body of method
}
}
A SIMPLE CLASS
// 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) {
// Creating 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);
// Calling 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” keyword
// Creating objects
BankAccount account = new BankAccount(); to create object
// Print balance
System.out.println(“Balance before deposit: " + account.balance);
// Calling 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; account
account.name = “Rashid”;
account.id = “1000500”;
account.balance = 1000;
name = Rashid
account reference
id = 1000500
balance = 1000
CREATE OBJECT AND ACCESS MEMBERS
public class TestBankAccount {
public static void main(String[] args) {
// Creating 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;
// Calling methods
accountK.deposit(2000);
// Print balance of both account
System.out.println("Kashem's balance: " + accountK.balance);
System.out.println("Rashid's balance: " + accountR.balance);
}
}
Output:
Kashem's balance: 3000.0
Rashid's balance: 1000.0
REFERENCE VARIABLE
Before deposit
name = Rashid
accountR reference
id = null
balance = 1000.0
name = Kashem
accountK reference
id = null
balance = 1000.0
After deposit:
name = Rashid
accountR reference
id = null
balance = 1000.0
name = Kashem
accountK reference
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;
}
// Methods
public void deposit(double amount){
balance = balance + amount;
}
public void withdraw(double amount){
if (amount<balance)
balance -= amount;
}
0 0
0 1
0
0
0
simpleArray reference 0
0
0
0 8
0
9
ARRAY AGAIN
When an array is created, each element will be
initialized to its default value.
What is the initial value for each of the element
of the arrays below.
int[] sampleArray = new int[10];
Student[] students = new Student[10];
REFERENCE TYPE WITH NOT NULL
Student student = new Student(“Rashid”, “011153001”, 3.0f, 50);
name = Rashid
student reference id = 011153001
cgpa= 3.0f
creaditCompleted = 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;
student null
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
students reference
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
cgpa= 3.0f
Ref creaditCompleted = 50
name = Zaman
students reference id = 011153021
Ref cgpa= 3.0f
creaditCompleted = 50
Ref name = Lubna
id = 011153031
cgpa= 3.5f
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
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
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
Before the method call Object
reference testName= “CT1”
score = 10.0f;
Heap
Stack
name = Rashid
id = 1000500
balance = 1000.0
accountR reference
name = Kashem
accountK reference
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
Stack
name = Rashid
id = 1000500
balance = 1000.0
accountR reference
name = Kashem
accountK reference
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);
Heap
Stack
name = Rashid
id = 1000500
balance = 1000.0
accountR reference
name = Kashem
accountK reference
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
Stack
name = Rashid
id = 1000500
balance = 1000.0
accountR null
name = Kashem
accountK reference
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);
}
testName= “CT1”
score = 15.0f; Heap
PACKAGE
WHAT IS PACKAGE?
Packages are used to group related classes.
A package is a namespace that organizes a set of
related classes and interfaces.
Conceptually you can think of packages as being
similar to different folders on your computer.
WHAT IS PACKAGE?
Classes in same package can not have duplicate
name.
Classes in different packages can have the same
name.
Class1
Package2 Class2
Package2_2 Class1
Package1
Class1
Package3
Class1 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 Class2
Package2_2 Class1
Package1
Class1
Package3
Class3
WHAT IS PACKAGE?
Classes in same package can not have duplicate
name.
Classes in different packages can have the same
name.
Class1
Package2 Class2
Package2_2 Class1
Package1
Class1
Package3
Class3
HOW TO CREATE PACKAGE?
To create a package is quite easy:
simply include a package command as the first
statement in a Java source file.
package pkg;
Any classes declared within that file will belong to
the specified package.
Java 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.println( "Hello for Test class." );
}
}
1. The class must be in a file named “Test.java"
2. Place the file “Test.java" in a directory called “cse"
3. Place directory “cse" in a directory called “uiu”.
4. The directory “cse" can be placed anywhere, but you
need to set the classpath.
PACKAGE -EXAMPLE
If you use IDE,
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.
Pack2 Class2