You are on page 1of 78

OOP-JAVA

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

public class BankAccount {


// Instance variables
public String name;
public String id;
public double balance;

// Methods
public void
deposit(double
amount){
balance = balance +
amount;
}

public void withdraw(double amount){


if (amount<balance)
balance -= amount;
}
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

// Assigning values to instance variables


account.name = "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);
// 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 = new BankAccount();


name = null
account reference
id = null
balance = 0.0

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

public void calculateInterest(double balance)


{
float interest; // accessible to anywhere inside the method.
if(balance > 10000)
{
interest = 0.05f; // Ok
}
else
{
interest = 0.02f; // OK
}
}
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.
Using Objects as Parameters

So far, we have only been using simple types as


parameters to methods. However, it is both correct
and common to pass objects to methods.
class Test {
int a, b;
Test(int i, int j)
{
a = i;
b = j;
}
boolean equals (Test o){
if( o.a == a && o.b == b)
return true;
else
return false;
}
}
class PassOb {
public static void main(String args[]) {

Test ob1 = new Test(100, 22);


Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);

System.out.println("ob1 == ob2: " + ob1.equals(ob2));


System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
Returning Objects

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[]) {

Test ob1 = new Test(2);


Test ob2;
ob2 = ob1.incrByTen();

System.out.println("ob1.a: " + ob1.a);


System.out.println("ob2.a: " + ob2.a);

ob2 = ob2.incrByTen();

System.out.println("ob2.a after second increase: “ + ob2.a);


}
}
Output:

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

 Not accessible outside the package that contains 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 DefaultExample {
public static void main( String[] args ) {
Default dfl= new Default();
System.out.println( dfl.name ); // Compile error
}
}
Class under same package
package test;
class DefaultExample1 {
public static void main( String[] args ) {
Default dfl = new Default();
System.out.println( dfl.name ); // OK
}
}
DEFAULT/PACKAGE ACCESS - EXAMPLE

Child Class under different package


package test1;
class DefaultChild extends Default {
public DefaultChild() {
name = “Child”; // Compile error
}
}

Child Class under same package


package test;
class DefaultChild1 extends Default {
public DefaultChild1() {
name = “Child”; // OK
}
}
PROTECTED
 Members declared protected are directly accessible to any subclasses,

 Even if the child is in different package


 directly accessible by code in the same package.
PROTECTED - EXAMPLE
Class that will be accessed from other classes
package test;
class Protected {
protected
String name
=
"Protected“;
}

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

Child Class Under Different Package


package test1;
class ProtectedChild extends Protected {
public ProtectedChild() {
pr.name = “Child”; // OK
}
}

Child Class Under Same Package


package test;
class ProtectedChild1 extends Protected {
public ProtectedChild1() {
pr.name = “Child”; // OK
}
}
PUBLIC

 Members declared public are accessible anywhere the class


is accessible.
 All the scenario described in other 3 types of access
modifier won’t give any compile error.
ACCESS MODIFIER CHART
Introducing Access Control
class Test {
int a; // default access
public int b; // public access
private int c; // private access

void setc(int i) { // set c's value


c = i;
}
int getc() { // get c's value
return c;
}
}
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
ob.a = 10;
ob.b = 20;

ob.c = 100; // You must access c through its methods

ob.setc(100); // OK

System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " +


ob.getc() );
}
}
Usage of THIS keyword

• this can be used to refer current class instance


variable.
• this can be used to invoke current class method.
• this() can be used to invoke current class
constructor.
1) this: to refer current class instance variable
class Student{
int ID;
String name;
float cgpa;
Student(int ID,String name,float cgpa){
this.rollno=rollno;
this.name=name;
this.cgpa=cgpa;
}
void display(){
System.out.println(ID+" "+name+" "+cgpa);}
}
class StudentTestThisExample1{
public static void main(String args[]){
Student s1=new Student(101,“Kabir", 3.4);
Student s2=new Student(102,“Sayma",3.9);
s1.display();
s2.display(); }}
2) this: to invoke current class method

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

• Calling default constructor from parameterized 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.

The static can be:


1. variable (also known as class variable)
2. method (also known as class method)
Java Program to demonstrate the use of static variable
class Student{
int id;
String name;
static String university =“UIU"; //static variable
//constructor
Student(int id, String name){
this.id = id;
this.name = name;
}
//method to display the values
void show (){
System.out.println(id+" "+name+" "+university);}
}
public class TestStaticMain{
public static void main(String args[]){
Student a = new Student(101,“Rahim");
Student b = new Student(102,“Karim");
//we can change the college of all objects by the single line of code
//Student.college=“UIU-2";
a.show();
b.show(); }}
Program of the counter without static variable
• Since instance variable gets the memory at the time of object creation, each object will have the copy of

the instance variable. If it is incremented, it won't reflect other 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

Why is the Java main method static?


• It is because the object is not required to call a static method. If it were a non-static
method, JVM creates an object first then call main() method that will lead the
problem of extra memory allocation.
Garbage Collection

• Garbage collection is a mechanism to remove objects from


memory when they are no longer needed.
• Garbage collection is carried out by the garbage collector:
1) The garbage collector keeps track of how many
references an object has.
2) It removes an object from memory when it has no
longer any references.
3) Thereafter, the memory occupied by the object can be
allocated again.
4) The garbage collector invokes the finalize method.

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.

Advantage of Garbage Collection:


• It makes java memory efficient because garbage collector
removes the unreferenced objects from heap memory.
• It is automatically done by the garbage collector(a part of
JVM) so we don't need to make extra efforts.
How can an object be unreferenced?

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

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#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);
}

static void updateScore(Test test, float newScore) {


test.score = newScore;
}
}

public class Test{


String testName;

float score;

Test(String n, float s){


testName = n;
score= s;
}
}
GARBAGE COLLECTION – SCENARIO#3

 At the beginning of method call

test testName= “CT1” Heap


reference score = 10.0f;

 After exiting the method.


 “test” variable will no longer be available.
 The Test object can no longer be accessed and is eligible for
garbage collection.

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 {

private int stck[] = new int[10];


private int tos;

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();

// push some numbers onto the stack


for(int i=0; i<10; i++) mystack1.push(i);
for(int i=10; i<20; i++) mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());

System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());

// these statements are not legal


// mystack1.tos = -2;
// mystack2.stck[3] = 100;
}
}
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?
o A java package is a group of similar types of classes, interfaces and
sub-packages.

o The package is an encapsulation mechanism it is binding the


related classes and interfaces.

o Package in java can be categorized in two form, built-in package


and user-defined package.

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.

The packages are divided into two types:

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.

 Third, packages provide a level of security,


 Can define classes inside a package that are not
accessible by code outside that package.
 can also define class members that are exposed only to
other members of the same package.
HOW TO ACCESS CLASS
 To use a class in same package, you can use the
class name (short name).
 To use a class in a different package, you must
tell Java the full name of the class.
 You use either an Import statement at the top of your
source code, and use short name or
 you can type the full name every place you use the
class in your code.

 java.lang.* package is always implicitly get


imported by Java. [ explicit import is not needed
for this package]
CLASS IN SAME PACKAGE
 Test Class
package uiu.cse;
public class Test{
public void
display() {
System.out.p
rintln( "Hell
o for Test
class." );
}
}
 Main Class
package uiu.cse;
public class
TestMain {
public static void main(String[] args) {
Test test = new Test();
test.display();
CLASS IN DIFFERENT PACKAGE – FULL
NAME
 Test Class
package uiu.cse;
public class Test{
public void
display() {
System.out.p
rintln( "Hell
o for Test
class." );
}
}
 Main Class
package
uiu.cse.test; //
any package
other than
uiu.cse
CLASS IN DIFFERENT PACKAGE - IMPORT
 Test Class
package uiu.cse;
public class Test{
public void
display() {
System.out.
println( "He
llo for Test
class." );
}
}
 Main Class
import uiu.cse.Test; // Need to import the class.
public class TestMain {
public static void main(String[] args)
{ Test test = new Test(); // use Short
name test.display();
}
}
 To import all classes under a
How to access package from another
package?

There are three ways to access the package from


outside the package.

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

You might also like