unit 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 83

Object Oriented Programming using Java

Unit-2

Subject Teacher : Dr. K. V. Metre

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 1


Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 2
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 3
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 4
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 5
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 6
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 7
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 8
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 9
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 10
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 11
Classes and Objects
• The class is the unit of programming
• A Java program is a collection of classes
– Each class definition (usually) in its own .java file
– The file name must match the class name
• A class describes objects (instances)
– Describes their common characteristics: is a blueprint
– Thus all the instances have these same characteristics
• These characteristics are:
– Data fields for each object
– Methods (operations) that do work on the objects

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 12


Class syntax:
class classname{
datatype instance_variable1;

Datatype instance_variable;

datatype methodname1(parameter_list)
{
//body of mehod
}
datatype methodname2(argument_list)
{
//body of method
}
}

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 13


Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 14
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 15
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 16
• What is an Object?
Real world objects are things that have:
1) state 2) behavior
Example: your dog:
state – name, color, breed,
behavior – sitting, barking, running
A software object is a bundle of variables (state)
and methods (operations).

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 17


Class :
Is a group of data and methods (functions).
Object :
Is an instance of a class, which is similar to a
variable, defined as an instance of a type. An
object is what you actually use in a program since
it contains values and can be changed.
Method :
Is a function contained within the class. You will
find the functions used within a class often
referred to as methods in programming
literature.

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 18


Stds

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 19


Creating object:
• To access the properties and methods of a class, we must
declare a variable of that class type.
• This variable does not define an object. Instead, it is simply a
variable that can refer to an object.
• We must acquire an actual, physical copy of the object and
assign it to that variable.
• We can do this using new operator.
• The new operator dynamically allocates memory for an
object and returns a reference to it.
• This reference is, more or less, the address in memory of the
object allocated by new.
• This reference is then stored in the variable.
• Thus, in Java, all class objects must be dynamically allocated.

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


20
University
New operator

• Using the new keyword in java is the most basic way


to create an object. This is the most common way to
create an object in java.
• By using this method we can call any constructor we
want to call (no argument or parameterized
constructors).
Example:

• mybox = new Box();

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


21
University
Object Creation Process
Object Creation Process involves following steps
E.g. Box name = new Box( );
1. new operator causes construction of the object Dynamically
2. JVM gives default values to the instance variables of Object
3. All static and non-static blocks are executed
4. Constructor is Executed
5. new operator binds the object to reference variable

Heap Stack
E.g.
null name
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 22
class Box //define a class
{ private :
int length;
int breadth;
int height;
public :
void setdata(int l, int b, int h) //member function to set data
{ length = l; breadth = b; height = h; }
void showdata() //member function to display data
{ System.out.println(“length =“+length+ “breadth =“+breadth+”height
=“+height);}
public static void main( String args[])
{ Box b1 = new Box();
b1.setdata(10,20,30);
b1.showdata();
}
} Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 23
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University
24
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University
25
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University
26
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University
27
Constructors

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 28


Constructors .

● It is set of Instructions designed to perform initial activities or


task after an object creation is completed
● Constructor is a special method in java
● Constructor must not have any return type
● The name of the constructor is same as the name of the class
● Constructor can have any access modifier
● If Constructor have private modifier, object can’t be created
from other classes.
● Every constructor has, as its first statement, either call to
other constructor of same class or call to its super class
constructor Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 29
Types of Constructors

Constructors are of two type

1) Default Constructor
This constructor is generated by the compiler when the
user don’t write any constructor

2) User Defined Constructor


This is the constructor written by the user in his program

There are two types of User defined Constructor


1. No-Argument Constructor
2. Parameterized Constructor

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 30


Constructor Overloading
● Constructor overloading, in this the name remains the same
just the arguments change
● In this the return type may or may not change
● To call the super class constructor use the “super” keyword
● This Mechanism is similar to Method Overloading
class Game{
public Game( ){ }
public Game(int i) { }
public Game( String a, String b){ }

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 31


class Box //define a class
{ private
int length;
int breadth;
int height;
public
Box() {length = 10; breadth = 10; height = 10};
Box(int l, int b, int h ) {length = l; breadth = b; height = h; }
void setdata(int l, int b, int h) //member function to set data
{ length = l; breadth = b; height = h; }
void showdata() //member function to display data
{ System.out.println(“length =“+length+ “breadth =“+breadth+”height =“+height);}
public static void main( String args[])
{ Box b1 = new Box();
// b1.setdata(10,20,30);
System.out.println("\nNo argument Constructor values: \n");
b1.showdata();

Box b2 = new Box(10,20,30);


System.out.println("\nParameterized Constructor values: \n");
b2.showdata();
}
} Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 32
Using Object as a Parameters
• When we pass a primitive type to a method, it is passed by value.
• But when we pass an object to a method, objects are passed by
call-by-reference.
• Java does this interesting thing that’s sort of a hybrid between
pass-by-value and pass-by-reference.
• While creating a variable of a class type, we only create a reference
to an object.
• Thus, when we pass this reference to a method, the parameter
that receives it will refer to the same object as that referred to by
the argument.
• This effectively means that objects act as if they are passed to
methods by use of call-by-reference.
• Changes to the object inside the method do reflect in the object
used as an argument. Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 33
Parameterized Constructor-2
// Java program to demonstrate one object to // driver class
initialize another
public class Test {
class Box
public static void main(String args[])
{ double width, height, depth;
{
// It takes an object of type Box. This constructor
// creating a box with all dimensions
use one object to initialize another
specified
Box(Box ob)
Box mybox = new Box(10, 20, 15);
{ width = ob.width;
// creating a copy of mybox
height = ob.height;
Box box1 = new Box(mybox);
depth = ob.depth;
double vol;
}
// get volume of mybox
// constructor used when all dimensions specified
vol = mybox.volume();
Box(double w, double h, double d)
System.out.println("Volume of mybox is " +
{ width = w;
vol);
height = h;
// get volume of box1
depth = d; }
vol = box1.volume();
double volume() // compute and return volume
System.out.println("Volume of box1 is " +
{ return width * height * depth; } vol); }
} } ITM SLS Baroda University
Dr. K. V. Metre, SOCSET, 34
Constructor Chaining
● Constructor Chaining is calling of the other
constructor of same class
● Constructor Chaining is possible with this keyword
● this must be the first statement of the constructor
body
● this can be parameterized or non parameterized
● super keyword is used to call super class constructor

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 35


Method Overloading/ Polymorphism

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 36


Method Overloading
● Method Overloading is the mechanism in which the methods
have same name but different signature
● Method Overloading happens in the same class
• Advantage of method overloading
Method overloading increases the readability of the program.

• There are 3 ways to overload the method in java


1) By changing number of arguments
add(int, int)
add(int, int, int)
2) By changing the data type of arguments
add(int, int) add( 2, 5)
add(int, float) add( 5, 10.5)
3) By changing Sequence of Data type of parameters.
add(int, float)
add(float, int)
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 37
● Signature of the Overloaded method should be Different
● Overloaded methods are not required to have the same
return type
if two methods have same name, same parameters and have
different return type, then this is not a valid method
Overloading
int add(int, int)
float add(int, int)
● This is similar to constructor overloading
● Subclass can Overload a inherited method of its base class
● Method overloading is an example of Static Polymorphism.

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 38


1. Static Polymorphism is also known as compile time binding
or early binding.

2. Static binding happens at compile time. Method


overloading is an example of static binding where binding of
method call to its definition happens at Compile time.

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 39


1) Method Overloading: changing no. of arguments
class Adder{
static int add(int a, int b)
{ return a+b;
}
static int add(int a, int b, int c)
{ return a+b+c;
} }
class TestOverloading1{
public static void main(String[] args){

System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output :
22
33
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 40
2) Method Overloading: changing data type of arguments
class Adder{
static int add(int a, int b){
return a+b;
}
static double add(double a, double b){
return a+b;
}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

Output
22
24.9
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 41
3) Method Overloading: changing sequence of arguments
class Adder{
static float add(int a, float b){
return a+b;
}
static float add(float a, int b){
return a+b;
}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11.0)); //method is defined as static
System.out.println(Adder.add(12.3,12));
}}

Output
22.0
24.3
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 42
• Can we overload java main() method?
• Yes, by method overloading. You can have any number of
main methods in a class by method overloading.
But JVM calls main() method which receives string array as
arguments only.

class TestOverloading{
public static void main(String[] args){
System.out.println("main with String[]");}
public static void main(String args){
System.out.println("main with String");}
public static void main(){
System.out.println("main without args");}
}
• Output:
main with String[]
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 43
Returning a value
• Method returns value

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 44


class Box //define a class
{ private
int length;
int breadth;
int height;
public
Box() {length = 10; breadth = 10; height = 10;};
Box(int l, int b, int h ) {length = l; breadth = b; height = h; }
void setdata(int l, int b, int h) //member function to set data
{ length = l; breadth = b; height = h; }
void showdata() //member function to display data
{
System.out.println("length ="+length+"breadth ="+ breadth+"height ="+height);}
int volume()
{ return length*breadth*height;}

public static void main( String args[])


{ Box b1 = new Box();
// b1.setdata(10,20,30);
System.out.println("\n No argument Constructor values: \n");
b1.showdata();
int v = b1.volume();
System.out.println("\n Volume = “+v);
Box b2 = new Box(10,20,30);
System.out.println("\nParameterized Constructor values: \n");
b2.showdata();
} Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 45
}
passing objects to methods
// Java program to demonstrate objects passing to
methods. • Output:
class Demo
{ int a, b;
ob1 == ob2: true
Demo(int i, int j) ob1 == ob3: false
{
a = i; b = j;
}
// return true if o is equal to the invoking object
boolean equalTo(Demo o)
{
return (a == o.a && b == o.b ); }
}
public class Test
{
public static void main(String args[])
{
Demo ob1 = new Demo(100, 22);
Demo ob2 = new Demo(100, 22);
Demo ob3 = new Demo(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
System.out.println("ob1 == ob3:Dr. K. V."Metre,
+ ob1.equalTo(ob3));
SOCSET, ITM SLS Baroda
46
University
} }
class Box
// driver class
{ double width, height, depth;
Box(Box ob) { public class Main
width = ob.width; {
height = ob.height; public static void main(String args[])
depth = ob.depth; {
} // creating a box with all dimensions
Box(double w, double h, double d)
Box b1 = new Box(10, 20, 15);
{ width = w;
Box b2 = new Box(10, 20, 30);
height = h;
Box t = new Box();
depth = d; }
void add( Box b1) t= b1.add(b2);
{ double w, h, d; t.show(); }
w = width + b1.width; }
h = height + b1.height;
d = depth + b1.depth; • Output :
Box ans = new Box( w, h, d); After add
ans.show(); }
Width = 20.0
void show()
{ System.out.println("After add " ); Height = 40.0
System.out.println("Width = " + width); Depth = 45.0
System.out.println("Height = " + height);
System.out.println("Depth = " + depth);
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 47
}}
Methods returning objects
class Box
{ private Class Test {
int length; public static void main( String args[])
int breadth; { Box b1 = new Box(20,20);
b1.showdata();
public int a = b1.area();
Box() {length = 0; breadth = 0; } System.out.println("\n Area ="+ a);
Box(int l, int b ) {
length = l; breadth = b; }
Box b2 = new Box(10,20);
void setdata(int l, int b) //member function to set data
{ length = l; breadth = b; }
b2.showdata();
void showdata() //member function to display data
{ Box b3 = b1.add(b2);
b3.showdata();
System.out.println("length="+length+"\tbreadth }
="+ breadth); }
} Output :
int area()
{ return length*breadth; }
length=20 breadth =20
Box add( Box b2) Area =400
{ length=10 breadth =20
Box temp = new Box(); length=30 breadth =40
temp.length = length + b2.length;
temp.breadth = breadth + b2.breadth;
return temp;
}
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 48
Returning Objects
• In java, a method can return any type of data, // Driver class
including objects.
public class Test
• the incrByTen( ) method returns an object in
{
which the value of a (an integer variable) is ten
greater than it is in the invoking object. public static void main(String args[])
// Java program to demonstrate returning of objects {
class Demo Demo ob1 = new Demo(2);
{ int a; Demo ob2;
Demo() { ob2 = ob1.incrByTen();
a = 0; }
Demo(int i) { System.out.println("ob1.a =" + ob1.a);
a = i; } System.out.println("ob2.a = " + ob2.a);
Demo incrByTen() // This method returns an object }
{ }
Demo temp = new Demo(); Output:
temp.a = a + 10; ob1.a =2
return temp; ob2.a = 12
}
} Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 49
this keyword in Java
• There can be a lot of usage of Java this keyword.
• In Java, this is a reference variable that refers to the
current object.

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 50


.

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 51


class Student{
int rollno; • OUTPUT
String name; 0 null 0.0
float fee; 0 null 0.0

Student(int rollno, String name, float fee)


parameters (formal
{ rollno = rollno; arguments) and instance
name = name; variables are same.
fee = fee; }
void display(){
System.out.println(rollno+" "+name+" "+fee);} }
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f); Stude
nt s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}} Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 52
Using this keyword
class Student{ • Output :
int rollno; 111 ankit 5000.0
String name; 112 sumit 6000.0
float fee;
Student(int rollno,String name,float fee){ If local variables(formal
this.rollno=rollno; arguments) and instance
this.name=name; variables are different, there
this.fee=fee; is no need to use this
keyword
}
Student(int r, String n, float f )
void display(){System.out.println(rollno+" "+name+" "+fee);
} {
} rollno=r;
name=n;
class TestThis2{ fee=f;
public static void main(String args[]){ }
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 53


2) this: to invoke current class method
invoke the method of the current class by using the this keyword.
If you don't use the this keyword, compiler automatically adds this
keyword while invoking the method
• Output

class A{ hello n hello m


void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();
this.m();
}
}
class TestThis4{
public static void main(String args[]){
A a=new A();
a.n();
}}

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 54


• 2) this: to invoke current class method

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 55


3) this() : to invoke current class constructor
• this() constructor call can be used to invoke the current class
constructor.
• It is used to reuse the constructor. it is used for constructor chaining. Calling
default constructor from parameterized constructor:
class A{
A( ){
System.out.println("hello a");} output : hello a
A(int x){ 10
this();
System.out.println(x);
}
}
class Test{
public static void main(String args[]){
A a=new A(10);
}}
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 56
Calling parameterized constructor from default constructor:
• call to this() must be the first statement in constructor

class A{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class Test{
public static void main(String args[]){
A a=new A();
}}
Output : 5
hello a

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 57


Static keyword:
• static keyword in Java is used for memory management
mainly.
• We can apply static keyword with variables, methods,
blocks and nested classes.
• The static keyword belongs to the class than an instance of
the class.
The static can be:
• Variable (also known as a class variable)
• Method (also known as a class method)
• Block
• Nested class

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 58


1) Java static variable
• If you declare any variable as static, it is known as a
static variable.
• The static variable can be used to refer to the common
property of all objects (which is not unique for each
object),
• 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.
class Student{
int rollno;
String name;
static String college = "ITM";
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 59
ITM

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 60


Java static variable
class Student{ public class Test{
int rollno;//instance variable public static void main(String args[]){
Student.change();//calling change met
String name; hod
static String college ="ITM";//sta //creating objects
tic variable Student s1 = new Student(111,"Karan"
);
//constructor Student s2 = new Student(222,"Aryan"
);
Student(int r, String n){ Student s3 = new Student(333,"Sam");
rollno = r;
name = n; //calling display method
} s1.display();
//method to display the values s2.display();
s3.display();
void display (){System.out.printl }
n(rollno+" "+name+" "+college);} }
} Output: 111 Karan ITM
222 Aryan ITM
Dr. K. V. Metre, SOCSET, ITM SLS Baroda 333 Sam ITM 61
University
static variable will get the memory only once, if any object changes the value

of the static variable, it will retain its value .


//Java Program to demonstrate the use of an instance va //Java Program to demonstrate the use of an instance va
riable riable
//which get memory each time when we create an objec //which get memory each time when we create an objec
t of the class. t of the class.
class Counter{ class Counter{
int count=0; int count=0;
//will get memory each time when the instance is cr //will get memory each time when the instance is cr
eated eated

Counter(){ Counter(){
count++;//incrementing value count++;//incrementing value
System.out.println(count); System.out.println(count);
} }

public static void main(String args[]){ public static void main(String args[]){
//Creating objects //Creating objects
Counter c1=new Counter(); Counter c1=new Counter();
Counter c2=new Counter(); Counter c2=new Counter();
Counter c3=new Counter(); Counter c3=new Counter();
} }
} }
Output: Output:
1 1
1 2
1 3

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 62


2) 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 the


object of a class.

• A static method can be invoked without the need for


creating an instance of a class.

• A static method can access static data member and


can change the value of it.

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 63


2) Java static method
//Java Program to get the cube of a given number using the static method
class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}
Output : 125
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 64
2) Java static method
Restrictions for the static method:
• static method can not use non static data member
or call non-static method directly.
• this and super cannot be used in static context.

class A{
int a=40;//non static
public static void main(String args[]){
System.out.println(a);
} }
Output : Compile Time Error
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 65
2) 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 the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
//Java Program to demonstrate the use of a static method. //Test class to create and display the values of
object
class Student{ public class TestStaticMethod{
int rollno;
String name; public static void main(String args[]){
static String college = “ITM";
Student.change();//calling change method
//static method to change the value of static variable //creating objects
static void change(){
college = “ITM SLS"; Student s1 = new Student(111,"Karan");
} Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//constructor to initialize the variable //calling display method
Student(int r, String n){
rollno = r; s1.display();
name = n; s2.display();
} s3.display();
//method to display values }
|
void display(){
System.out.println(rollno+" "+name+" "+college);}
}
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 66
Restrictions for the static method

There are two main restrictions for the static method.


1) The static method can not use non static data member or call non-
static method directly.
2) this and super cannot be used in static context.

class A{
int a=40;//non static

public static void main(String args[]){


System.out.println(a);
}
}

Output:
Compile Time Error

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


67
University
3) Java static block
• Is used to initialize the static data member.
• It is executed before the main method at the time of
class loading.
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output : static block is invoked
Hello main
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 68
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.

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 69


Access Modifier

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 70


Access Modifiers in Java
• As the name suggests access modifiers in Java
helps to restrict the scope of a class, constructor,
variable, method, or data member.
There are four types of access modifiers available
in java:
• Default – No keyword required
• Private
• Protected
• Public

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 71


Java has 3 Access Modifier and 4 Accessibility Modes
● Public
The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the
package.
● Private
The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
● Protected
The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
● Default
• When no access modifier is specified for a class, method, or data member –
It is said to be having the default access modifier by default.
• The data members, class or methods which are not declared using any
access modifiers i.e. having default access modifier are accessible only
within the same package.
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 72
Visibility Control
Modifier public Protected default Private
(friendly)
Access
Control
Same Class Yes Yes Yes Yes
Subclass in Same Yes Yes Yes No
Package
Other Class in Yes Yes Yes No
same Package
Subclass in other Yes Yes No No
Package
Non-subclasses in Yes No No No
other package Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 73
Example of private access modifier

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
If you make any class constructor private, you cannot create the
instance of that class from outside
Dr. K. V. Metre, theSLS class
SOCSET, ITM Baroda University 74
Example of public access modifier
/save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

• Output : Hello Dr. K. V. Metre, SOCSET, ITM SLS Baroda


75
University
Example of protected access modifier
//save by A.java
package pack;
public class A{
protected void msg()
{ System.out.println("Hello"); }
}
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}

Output : Hello Dr. K. V. Metre, SOCSET, ITM SLS Baroda


University
76
Example of default access modifier
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
since A class is not public, so it cannot be accessed from outside the package.
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 77
Java Object finalize() Method :
• Finalize() is the method of Object class.
• This method is called just before an object is garbage collected.
• finalize() method overrides to dispose system resources,
perform clean-up activities and minimize memory leaks.
• The primary purpose of the finalize() method is to allow an
object to perform cleanup operations, such as releasing
resources or closing connections, before it is removed from
memory.
• While the use of finalize() has been somewhat deprecated in
modern Java in favor of other mechanisms (such as try-with-
resources and AutoCloseable), it's still worth understanding its
importance.

• Syntax :
protected void finalize() throws Throwable
Throwable - the Exception is raised by this method
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 78
public class Test {
public static void main(String[] args)
{
Test obj = new Test();
System.out.println(obj.hashCode());
obj = null;
// calling garbage collector
System.gc();
System.out.println("end of garbage collection");

}
@Override
protected void finalize()
{
System.out.println("finalize method called");
} }
Output : 2018699554
end of garbage collection
finalize method called
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 79
Recursion
• Each time a method is called, a new space is allocated on
the internal stack for all the variable in the method, which
means there is no reason you can’t call the same method
again – a new set of variables will be allocated on the stack
automatically
• Recursion is a technique in which a method calls itself.
• This technique provides a way to break complicated
problems down into simple problems which are easier to
solve.
• Examples of recursion are:
• Factorial of number
• Fibonacci series

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 80


Recursion
static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));

public static void main(String[] args) {


System.out.println("Factorial of 5 is: "+factorial(5));
}
}
Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 81
Recursion
• Each time a method is called, a new space is allocated on
the internal stack for all the variable in the method, which
means there is no reason you can’t call the same method
again – a new set of variables will be allocated on the stack
automatically
• Recursion is a technique in which a method calls itself.
• This technique provides a way to break complicated
problems down into simple problems which are easier to
solve.
• Examples of recursion are:
• Factorial of number
• Fibonacci series

Dr. K. V. Metre, SOCSET, ITM SLS Baroda University 82


End of Unit-2

Dr. K. V. Metre, SOCSET, ITM SLS Baroda


83
University

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy