Professional Documents
Culture Documents
Class-Object
&
Scope & Lifetime of Variables
&
Object Passing, Access control, Static, this
Md. Rayhan Ahmed
Assistant Professor
Dept. of CSE
United International University
A SIMPLE CLASS
// Methods
public void
deposit(double
amount){
balance = balance +
amount;
}
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);
}
}
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
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
class Test {
int a;
Test (int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}
class RetOb
{
public static void main(String args[]) {
ob2 = ob2.incrByTen();
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
ACCESS CONTROL/ACCESS MODIFIER
How a member can be accessed is determined by the
access modifier attached to its declaration.
4 types
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_Class {
private String name = "Private";
public void print() {
System.out.println( name );
}
}
class Private_ClassExample {
public static void main( String[] args ) {
Private_Class pr = new Private_Class();
pr.print(); // OK
System.out.println( pr.name ); // Compile error
}
}
DEFAULT/PACKAGE ACCESS
When no access modifier is specified
Accessible in the package that contains the class
Class Under
Different
Package
package test1;
class
ProtectedExam
ple {
public static void main( String[] args ) {
Protected pr = new Protected();
System.out.println( pr.name ); //
Compile error
}}
PROTECTED - EXAMPLE
ob.setc(100); // OK
class thistest{
void A(){
System.out.println("TEST A");}
void B(){
System.out.println("TEST B");
//m();//same as this.m()
this.A();
}
}
class thistestmain{
public static void main(String args[]){
thistest a=new thistest();
a.B();
}
}
3) this() : to invoke current class constructor
class A{
A(){
System.out.println(“TEST A");
}
A(int p){
this();
System.out.println(p);
}
}
class TestThisMain{
public static void main(String args[]){
A a=new A(10);
}
}
3) this() : to invoke current class constructor
• Calling parameterized constructor from default constructor:
class A{
A(){
this(5);
System.out.println(“TEST A");
}
A(int p){
System.out.println(p);
}
}
class TestThisMain{
public static void main(String args[]){
A a=new A();
}
}
Real usage of this() constructor call - Constructor Chaining
class Student{
int ID;
String name,course;
float fee;
Student(int ID,String name,String course){
this.ID=ID;
Rule: Call to this() must be the
this.name=name;
first statement in constructor.
this.course=course;
}
Student(int ID,String name,String course,float fee){
this(ID,name,course);//reusing constructor
this.fee=fee;
}
void show(){
System.out.println(ID+" "+name+" "+course+" "+fee);}
}
class TestThisMain{
public static void main(String args[]){
Student a=new Student(101,“Rakib",“OOP");
Student b=new Student(102,“Samiul",“OS",3600f);
a.show();
b.show(); }}
JAVA static keyword
• The static variable can be used to refer to the common property of all
objects (which is not unique for each object), for example, the
company name of employees, college name of students, etc.
• The static variable gets memory only once in the class area at the
time of class loading.
• It makes your program memory efficient (i.e., it saves memory).
• In Java - static property is shared to all objects.
class Counter{
int count=10; //will get memory each time when the instance is created
Counter(){
count++; //incrementing value
System.out.println(count);
}
Output:
11
public static void main(String args[]){ 11
11
Counter a=new Counter();
Counter b=new Counter();
Counter c=new Counter();
}
}
Program of the counter with static variable
• static variable will get the memory only once, if any object changes the value of the static variable, it
will retain its value.
class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;//incrementing the value of static variable
System.out.println(count);
}
Output:
11
public static void main(String args[]){
12
Counter2 a=new Counter2(); 13
Counter2 b=new Counter2();
Counter2 c=new Counter2();
}
}
Java static method
• If you apply static keyword with any method, it is
known as static method.
• A static method belongs to the class rather than object
of a class.
• A static method can be invoked without the need for
creating an instance of a class.
• static method can access static data member and can
change the value of it.
Java static method
class Student{ public class TestStaticMethod{
int id; public static void main(String args[]){
String name; Student.change();//calling change method
static String university = “UIU"; //creating objects
//static method to change the value of static Student a = new Student(101,“Reba");
variable Student b = new Student(102,“Rini");
static void change(){ Student c = new Student(103,“Rafiq");
university = “UIU-2"; //calling display method
} a.show();
//constructor to initialize the variable b.show();
Student(int id, String name){ c.show();
this.id = id; }
this.name = name; }
}
//method to display values
void show(){
System.out.println(rollno+" "+name+"
"+university);}
}
Restrictions for static method
There are two main restrictions for the static
method. They are:
• The static method can not use non static data
member or call non-static method directly.
• this and super cannot be used in static context
L 6.7
Garbage Collection
• To do so, we were using free() function in C language and
delete() in C++. But, in java it is performed automatically.
So, java provides better memory management.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for
garbage collection
3) By anonymous object:
new Employee();
GARBAGE COLLECTION – SCENARIO#1
• Heap
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
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);
}
float score;
testName= “CT1”
score = 15.0f; Heap
finalize() Method
• A constructor helps to initialize an object just after it
has been created.
• In contrast, the finalize method is invoked just before
the object is destroyed:
1) implemented inside a class as:
protected void finalize()
{…}
2) implemented when the usual way of removing
objects from memory is insufficient, and some special
actions has to be carried out
L 6.8
class Stack {
Stack() {
tos = -1;
}
void push (int item) {
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
// Pop an item from the stack
int pop() {
if(tos < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
o There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.
Advantage of Java Package
1) Java package is used to categorize the classes and
interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
1) Predefined packages
2) User defined packages
Example
WHAT IS PACKAGE?
Classes in same package can not have duplicate name.
Classes in different packages can have the same name.Class1
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
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.p
rintln( "Hell
o for Test
class." );
}
}
1. The class
must be in a
file named
“Test.java"
2. Place the file
“Test.java" in
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.
import package.*;
import package.classname;
fully qualified name.
Using packagename.*
If you use package.* then all the classes and interfaces of this package will be
accessible but not sub-packages.
package pack;
public class One{
public void msg(){
System.out.println(“OOP");}
}
package pack2;
import pack.*;
class Two{
public static void main(String args[]){
One obj = new One();
obj.msg();
}
}
Using packagename.classname
• If you import package.classname then only declared class of this
package will be accessible.
package pack;
public class One{
public void msg(){System.out.println(“OOP");}
}
package pack2;
import pack.One;
class Two{
public static void main(String args[]){
One obj = new One();
obj.msg();
}
}
Using fully qualified name
• If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
package pack;
public class One{
public void msg(){
System.out.println(“OOP");}
}
package pack2;
class Two{
public static void main(String args[]){
pack.One obj = new packOne();//using fully qualified name
obj.msg();
}
}
The End