0% found this document useful (0 votes)
3 views89 pages

Class Object

The document provides an overview of classes and objects in object-oriented programming, explaining the concepts of classes as blueprints for objects and the significance of instance variables and methods. It discusses the creation of objects, initialization of fields, and the scope and lifetime of variables in Java. Additionally, it covers constructors, the 'this' keyword, and the use of arrays in programming.

Uploaded by

mrh264475
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views89 pages

Class Object

The document provides an overview of classes and objects in object-oriented programming, explaining the concepts of classes as blueprints for objects and the significance of instance variables and methods. It discusses the creation of objects, initialization of fields, and the scope and lifetime of variables in Java. Additionally, it covers constructors, the 'this' keyword, and the use of arrays in programming.

Uploaded by

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

Class & Object

CSE 1115: Object Oriented Programming

1
Contents

 Class & Object.


 Initializing Fields/Instance variables.

 Scope & Lifetime of Variable.

 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.

 Once defined, this new type can be used to create

objects of that type.


⚫ Thus, a class is a template for an object,
⚫ and an object is an instance of a class.
⚫ Because an object is an instance of a class, you will
often see the two words object and instance used
interchangeably
CLASS MEMBERS
 Class contains the following 2 members
⚫ instance variables(fields/properties/attributes)
 each instance of the class (that is, each object of the
class) contains its own copy of these variables.
 Thus, the data for one object is separate and unique

from
the data for another.
⚫ Methods(action/behavior)
 The code is contained within methods
 In most classes, the instance variables are acted upon and

accessed by the methods defined for that class.


 Thus, as a general rule, it is the methods that determine

how a class’ data can be used.


THE GENERAL FORM OF
A CLASS
class classname {
datatype instance-variable1;
datatype instance-
variable2;
/ / ...
datatype instance-
variableN;

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

public void withdraw(double amount){


if (amount<balance)
balance -= amount;
}
CREATE OBJECT AND
ACCESS MEMBERS
 Creating objects – use new keyword
⚫ ClassName refVariable = new ClassName(parameter-list);

 To access instance variables and methods - use


dot operator(.)
⚫Accessing instance variables
 refVariable.instance_variable = value;
 Or
 datatype value = refVariable.instance_variable;

⚫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 = new BankAccount();


name = null
accoun reference
t id = null
balance = 0.0

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

public void withdraw(double amount){


if (amount<balance)
2.INSTANCE
INITIALIZATION BLOCK
 Instance initialization blocks are indicated by blocks
of code inside the class, but outside any method.
 Whenever an object is created from a class the code in
each instance initialization block is executed.
 If there is more than one instance initialization block
they are executed in order, from top to bottom of the
class.
 Use initialization blocks when the initialization
cannot be done in a simple assignment and needs no
extra input parameters.
 Direct assignment and constructors are used far
more often than initialization blocks.
2.INSTANCE
INITIALIZATION BLOCK
public class BankAccount {
// Instance variables
public String name;
public String id;
public double balance;

// M ethods
public void
deposit(double
amount){
balance = balance +
amount;
}
public void withdraw(double amount){
if (amount<balance)
balance -= amount;
}

{ // Instance Initialization Block


id = new Random().nextInt(99999) + "";
balance = 100.0;
3.CONSTRUCTOR
 A constructor
⚫ Allocate space for instance variables.
⚫ initializes an object(its instance variables)
immediately upon creation.
 Syntax:
⚫ It has the same name as the class.
⚫ syntactically similar to a method.
 Except has no return type. Not even void.
 This is because the implicit return type of a class’

constructor is the class type itself.


3.CONSTRUCTOR
 When called:
⚫ No explicit call
⚫ It is automatically called when the object is created,
before the new operator completes.
 What should go inside Constructor
⚫ Normally the instance variables are initialized inside
the constructor.
Or
⚫ any set-up code
3.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;
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.

 The default constructor automatically initializes all


instance variables to their default values,
⚫ Default value
 Boolean -> false;
 All primitive except boolean -> 0 (zero)
 Reference type -> null

 Once you define your own constructor, the default


constructor is no longer used.
“THIS”KEYWORD

 refer to the current object.


 That is, this is always a reference to the

object on which the method was invoked.


 You can use this anywhere a reference to an

object of the current class’ type is


permitted.
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){
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(99999) + "";
// name and balance will get default value
}

// Constructor with parameter


public BankAccount (String name, String id, double balance) {
name = name;
id = id; Variable on left is the same as
right What are we doing here
balance = balance;
Which variables we are referring to
}

public static void main(String[] args)


{
BankAccount ba = new BankAccount(“ Rashid ”, “1000500”, 1000.0);
}
}
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

 What is the “new” keyword during array creation.


 Is Array variable reference type?

int[] sampleArray = new int[10];


ARRAY AGAIN
 What is the “new” keyword during array creation.
 Is Array variable reference type?

int[] sampleArray = new int[10];


0 0
0 1
0
0
0
simpleArra reference 0
y
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
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

 In J a v a all parameters are passed by value


PASS BY REFERENCE – NOT
APPLICABLE IN JAVA
 Send the location of the parameter.
 Original value chage

 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

 After the function execution.


i 20 10
j
num num 10 tem
1 2 p
PASS BY VALUE
 Send a copy of the original parameter.
 Original value does not change

 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

 After the method execution.


i 10 20
j
num 20 10 num 10 tem
1 2 p
PASS BY VALUE
 Java Example:
public class PassByValue {
public static void main(String[] args) {
int a=10, b=20; Output:
System.out.printf("a-%d:b-%d\n", a,
a-10:b-20
b); swapThemByVal(a, b);
a-10:b-20
System.out.printf("a-%d:b-%d\n", a, b);
}

static 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

 After the method execution.


i 10 20
j
num 20 10 num 10 tem
1 2 p
PASS BY VALUE – WITH
OBJECT
 When an object is passed to a method, the
situation changes dramatically,
 Java will pass by value but the effect will be like

pass-by-reference.
 Why?

⚫ When we create a variable of a class type, it will store


the reference to an object.
⚫ Thus, when the value of the variable will be passed to
a method, it will pass the reference of the same
object.
⚫ This effectively means that objects act as if they are
passed to methods by use of pass-by-reference.
⚫ Changes to the object inside the method do affect the
object used as an argument.
PASS BY VALUE – WITH
OBJECT
public class
Test{ String
testName; float
score;

Test(String n, float s){


testName = n;
score = s;
}

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

static void updateScore(Test test, float newScore) {


test.score = newScore;
}
}

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;

 At the beginning of method call


⚫ Both “t” and “test” are referring to the same object.
⚫ Updating the object using any variable will be reflected in the other
one.
t reference testName= “CT1”
score = 10.0f;
tes reference
t

 Just at the end of method execution – before exiting the method


t reference testName= “CT1”
score = 15.0f;
tes reference
t
PASS BY VALUE – WITH
OBJECT
What is NOT happening:
The reference itself (the variable obj) is not changed.

public static void modify(MyClass obj) {


obj = new MyClass(); // Assign a new object to the
parameter
obj.x = 10; // This change is to the new object
}

public static void main(String[] args) {


MyClass obj = new MyClass();
obj.x = 5;
modify(obj);
System.out.println(obj.x); // Output: 5
}
GARBAGE
COLLECTION
GARBAGE
COLLECTION
 When no references to an object exist, that object is
assumed to be no longer needed, and the memory
occupied by the object can be reclaimed.
 Garbage collection only occurs sporadically (if at all)

during the execution of your program.


 Different Java run-time implementations will take

varying approaches to garbage collection,


 but for the most part, you should not have to think

about it while writing your programs.


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

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

BankAccount accountK = new BankAccount(“Kashem”, “1000501” , 10000.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

Stack balance = 1000.0

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

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
tes testName= “CT1” Hea
reference score = 10.0f;
t p

 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; Hea
p
PACKA
GE
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 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.

 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.
CLASS’S FULL
NAME
 A class has a full name, which is a combination of
the package name and the class name.
Class1 Full Name:
Pack1.Pack2.Class1
Pack2 Class2

Pack2_2 Class1 Full Name:


Pack1 Pack1.Pack2.Pack2_2.Class1
Class1
Pack3
Class3 Full Name:
Pack1.Pack3.Class3
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();
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
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 {
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

 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
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
}
}

Child Class under same package


package test;
class DefaultChild1 extends Default {
public DefaultChild1() {
name = “Child”; // O K
}
}
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
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
}
}

Child Class Under Same Package


package test;
class ProtectedChild1 extends Protected {
public ProtectedChild1() {
pr.name = “Child”; // O K
}
}
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
REFERENCE
 Java:Complete Reference Chapter 6,7,9

You might also like