0% found this document useful (0 votes)
36 views

Unit 3

Classes define the blueprint for objects by specifying their properties (data members) and behaviors (methods). An object is an instance of a class that allocates memory at runtime. The class defines common characteristics like breed, age, size for dogs while methods define behaviors like eating, sleeping. To create an object, a variable is declared and initialized using the new keyword followed by a constructor call. Objects can then access class methods and instance variables. A source file can contain one public class and multiple non-public classes if import and package declarations are written correctly.

Uploaded by

8sakshipatel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

Unit 3

Classes define the blueprint for objects by specifying their properties (data members) and behaviors (methods). An object is an instance of a class that allocates memory at runtime. The class defines common characteristics like breed, age, size for dogs while methods define behaviors like eating, sleeping. To create an object, a variable is declared and initialized using the new keyword followed by a constructor call. Objects can then access class methods and instance variables. A source file can contain one public class and multiple non-public classes if import and package declarations are written correctly.

Uploaded by

8sakshipatel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

UNIT-3

Class and Object:


classes and objects are the fundamental components of OOP's. Often there is a
confusion between classes and objects. In this tutorial, we try to tell you the
difference between class and object.

First, let's understand what they are,

 What is Class: A class is an entity that determines how an object will


behave and what the object will contain. In other words, it is a blueprint
or a set of instruction to build a specific type of object.

 What is an object: An object is nothing but a self-contained component


which consists of methods and properties to make a particular type of data
useful. Object determines the behavior of the class. When you send a
message to an object, you are asking the object to invoke or execute one
of its methods.

From a programming point of view, an object can be a data structure, a


variable or a function. It has a memory location allocated. The object is
designed as class hierarchies.

What is the difference between Object & class?


A class is a blueprint or prototype that defines the variables and the methods
(functions) common to all objects of a certain kind.

An object is a specimen of a class. Software objects are often used to model


real-world objects you find in everyday life.

Let understand the concept of Java classes and objects with an example.

Let's take an example of developing a pet management system, specially meant for
dogs. You will need various information about the dogs like different breeds of
the dogs, the age, size, etc.

You need to model real life beings, i.e., dogs into software entities.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


question is, how you design such software?

Here is the solution-

First, let's do an exercise.

You can see the picture of three different breeds of dogs below.

Stop here right now! List down the differences between them.

Some of the differences you might have listed out may be breed, age, size,
color, etc. If you think for a minute, these differences are also some common
characteristics shared by these dogs. These characteristics (breed, age, size,
color) can form a data members for your object.

Next, list out the common behaviors of these dogs like sleep, sit, eat, etc. So
these will be the actions for our software objects.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


So far we have defined following things,

 Class - Dogs
 Data members or objects- size, age, color, breed, etc.
 Methods- eat, sleep, sit and run.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Now, for different values of data members (breed size, age, and color) in Java
class, you will get different dog objects.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Some technical points about a class

1.One of the fundamental ways in which we handle complexity is in abstractions.


An abstraction denotes the essential properties and behaviors of an object that
differentiate it from other objects.

2. The essence of OOP is modelling abstractions, using classes and objects. The
hard part in this endeavor is finding the right abstraction.

3.A class denotes a category of objects, and acts as a blueprint for creating
such objects.

4.A class models an abstraction by defining the properties and behaviors for the
objects representing the abstraction. An object exhibits the properties and
behaviors defined by its class.

5. The properties of an object of a class are also called attributes, and are
defined by fields in Java. A field in a class is a variable which can store a
value that represents a particular property of an object. The behaviors of an
object of a class are also known as operations, and are defined using methods in
Java.Fields and methods in a class declaration are collectively called members.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Class declaration in JAVA
Following is a sample of a class.

Example
public class Dog {
String breed;
int age;
String color;

void barking() {
}

void hungry() {
}

void sleeping() {
}
}

A class can contain any of the following variable types.

 Local variables − Variables defined inside methods, constructors or blocks


are called local variables. The variable will be declared and initialized
within the method and the variable will be destroyed when the method has
completed.

 Instance variables − Instance variables are variables within a class but


outside any method. These variables are initialized when the class is
instantiated. Instance variables can be accessed from inside any method,
constructor or blocks of that particular class.

 Class variables − Class variables are variables declared within a class,


outside any method, with the static keyword.

A class can have any number of methods to access the value of various kinds of
methods. In the above example, barking(), hungry() and sleeping() are methods.

Following are some of the important topics that need to be discussed when
looking into classes of the Java Language.

Constructors
When discussing about classes, one of the most important sub topic would be
constructors. Every class has a constructor. If we do not explicitly write a
constructor for a class, the Java compiler builds a default constructor for that
class.

Each time a new object is created, at least one constructor will be invoked. The
main rule of constructors is that they should have the same name as the class. A
class can have more than one constructor.

Following is an example of a constructor −

Example
public class Puppy {
public Puppy() {

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


}

public Puppy(String name) {


// This constructor has one parameter, name.
}
}

Java also supports Singleton Classes where you would be able to create only one
instance of a class.

Note − We have two different types of constructors. We are going to discuss


constructors in detail in the subsequent chapters.

Creating an Object
As mentioned previously, a class provides the blueprints for objects. So
basically, an object is created from a class. In Java, the new keyword is used
to create new objects.

There are three steps when creating an object from a class −

 Declaration − A variable declaration with a variable name with an object


type.

 Instantiation − The 'new' keyword is used to create the object.

 Initialization − The 'new' keyword is followed by a call to a constructor.


This call initializes the new object.

Following is an example of creating an object −

Example
public class Puppy {
public Puppy(String name) {
// This constructor has one parameter, name.
System.out.println("Passed Name is :" + name );
}

public static void main(String []args) {


// Following statement would create an object myPuppy
Puppy myPuppy = new Puppy( "tommy" );
}
}

If we compile and run the above program, then it will produce the following
result −

Output
Passed Name is :tommy

Accessing Instance Variables and Methods


Instance variables and methods are accessed via created objects. To access an
instance variable, following is the fully qualified path −

/* First create an object */


ObjectReference = new Constructor();

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


/* Now call a variable as follows */
ObjectReference.variableName;

/* Now you can call a class method as follows */


ObjectReference.MethodName();

Example
This example explains how to access instance variables and methods of a class.

public class Puppy {


int puppyAge;

public Puppy(String name) {


// This constructor has one parameter, name.
System.out.println("Name chosen is :" + name );
}

public void setAge( int age ) {


puppyAge = age;
}

public int getAge( ) {


System.out.println("Puppy's age is :" + puppyAge );
return puppyAge;
}

public static void main(String []args) {


/* Object creation */
Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age */


myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */


myPuppy.getAge( );

/* You can access instance variable as follows as well */


System.out.println("Variable Value :" + myPuppy.puppyAge );
}
}

If we compile and run the above program, then it will produce the following
result −

Output
Name chosen is :tommy
Puppy's age is :2
Variable Value :2

Source File Declaration Rules


As the last part of this section, let's now look into the source file
declaration rules. These rules are essential when declaring classes, import
statements and package statements in a source file.

 There can be only one public class per source file.

 A source file can have multiple non-public classes.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


 The public class name should be the name of the source file as well which
should be appended by .java at the end. For example: the class name is
public class Employee{} then the source file should be as Employee.java.

 If the class is defined inside a package, then the package statement


should be the first statement in the source file.

 If import statements are present, then they must be written between the
package statement and the class declaration. If there are no package
statements, then the import statement should be the first line in the
source file.

 Import and package statements will imply to all the classes present in the
source file. It is not possible to declare different import and/or package
statements to different classes in the source file.

Classes have several access levels and there are different types of classes;
abstract classes, final classes, etc. We will be explaining about all these in
the access modifiers chapter.

Apart from the above mentioned types of classes, Java also has some special
classes called Inner classes and Anonymous classes.

Object reference:
Assigning Object Reference Variables : Class Concept in Java Programming
1. We can assign value of reference variable to another reference variable.
2. Reference Variable is used to store the address of the variable.
3. Assigning Reference will not create distinct copies of Objects.
4. All reference variables are referring to same Object.

Assigning Object Reference Variables does not –


1. Create Distinct Objects.
2. Allocate Memory
3. Create duplicate Copy

Consider This Example –

Rectangle r1 = new Rectangle();


Rectangle r2 = r1;

 r1 is reference variable which contain the address of Actual Rectangle


Object.
 r2 is another reference variable
 r2 is initialized with r1 means – “r1 and r2” both are referring same
object , thus it does not create duplicate object , nor does it allocate
extra memory.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Live Example : Assigning Object Reference Variables
class Rectangle {
double length;
double breadth;
}

class RectangleDemo {
public static void main(String args[]) {

Rectangle r1 = new Rectangle();


Rectangle r2 = r1;

r1.length = 10;
r2.length = 20;

System.out.println("Value of R1's Length : " + r1.length);


System.out.println("Value of R2's Length : " + r2.length);

}
}

Output :

Value of R1's Length : 20.0


Value of R2's Length : 20.0

Typical Concept :
Suppose we have assigned null value to r2 i.e

Rectangle r1 = new Rectangle();

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Rectangle r2 = r1;
.
.
.
r1 = null;

Note : Still r2 contain reference to an object. Thus We can create have multiple
reference variables to hold single object.

Method Overloading:
Method Overloading is a feature that allows a class to have two or more methods
having same name, if their argument lists are different.

Argument lists could differ in –


1. Number of parameters.
2. Data type of parameters.
3. Sequence of Data type of parameters.

Method overloading is also known as Static Polymorphism.

Points to Note:
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.

Method Overloading examples:


As discussed above, method overloading can be done by having different argument
list. Lets see examples of each and every case.

Example 1: Overloading – Different Number of parameters in argument list


When methods name are same but number of arguments are different.

class DisplayOverloading
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c, int num)
{
System.out.println(c + " "+num);
}
}
class Sample
{
public static void main(String args[])
{
DisplayOverloading obj = new DisplayOverloading();
obj.disp('a');
obj.disp('a',10);
}
}

Output:

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


a
a 10

In the above example – method disp() has been overloaded based on the number of
arguments – We have two definition of method disp(), one with one argument and
another with two arguments.

Example 2: Overloading – Difference in data type of arguments


In this example, method disp() is overloaded based on the data type of arguments
– Like example 1 here also, we have two definition of method disp(), one with
char argument and another with int argument.

class DisplayOverloading2
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(int c)
{
System.out.println(c );
}
}

class Sample2
{
public static void main(String args[])
{
DisplayOverloading2 obj = new DisplayOverloading2();
obj.disp('a');
obj.disp(5);
}
}

Output:

a
5

Example3: Overloading – Sequence of data type of arguments


Here method disp() is overloaded based on sequence of data type of arguments –
Both the methods have different sequence of data type in argument list. First
method is having argument list as (char, int) and second is having (int, char).
Since the sequence is different, the method can be overloaded without any
issues.

class DisplayOverloading3
{
public void disp(char c, int num)
{
System.out.println("I’m the first definition of method disp");
}
public void disp(int num, char c)
{
System.out.println("I’m the second definition of method disp" );
}
}

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


class Sample3
{
public static void main(String args[])
{
DisplayOverloading3 obj = new DisplayOverloading3();
obj.disp('x', 51 );
obj.disp(52, 'y');
}
}

Output:

I’m the first definition of method disp


I’m the second definition of method disp

Lets see few Valid/invalid cases of method overloading


Case 1:

int mymethod(int a, int b, float c)


int mymethod(int var1, int var2, float var3)

Result: Compile time error. Argument lists are exactly same. Both methods are
having same number, data types and same sequence of data types in arguments.

Case 2:

int mymethod(int a, int b)


int mymethod(float var1, float var2)

Result: Perfectly fine. Valid case for overloading. Here data types of arguments
are different.

Case 3:

int mymethod(int a, int b)


int mymethod(int num)

Result: Perfectly fine. Valid case for overloading. Here number of arguments are
different.

Case 4:

float mymethod(int a, float b)


float mymethod(float var1, int var2)

Result: Perfectly fine. Valid case for overloading. Sequence of the data types
are different, first method is having (int, float) and second is having (float,
int).

Case 5:

int mymethod(int a, int b)


float mymethod(int var1, int var2)

Result: Compile time error. Argument lists are exactly same. Even though return
type of methods are different, it is not a valid case. Since return type of
method doesn’t matter while overloading a method.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Guess the answers before checking it at the end of programs:
Question 1 – return type, method name and argument list same.

class Demo
{
public int myMethod(int num1, int num2)
{
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2)
{
System.out.println("Second myMethod of class Demo");
return var1-var2;
}
}
class Sample4
{
public static void main(String args[])
{
Demo obj1= new Demo();
obj1.myMethod(10,10);
obj1.myMethod(20,12);
}
}

Answer:
It will throw a compilation error: More than one method with same name and
argument list cannot be defined in a same class.

Question 2 – return type is different. Method name & argument list same.

class Demo2
{
public double myMethod(int num1, int num2)
{
System.out.println("First myMethod of class Demo");
return num1+num2;
}
public int myMethod(int var1, int var2)
{
System.out.println("Second myMethod of class Demo");
return var1-var2;
}
}
class Sample5
{
public static void main(String args[])
{
Demo2 obj2= new Demo2();
obj2.myMethod(10,10);
obj2.myMethod(20,12);
}
}

Answer:
It will throw a compilation error: More than one method with same name and
argument list cannot be given in a class even though their return type is
different. Method return type doesn’t matter in case of overloading.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Constructor in JAVA:
Constructor in java is a special type of method that is used to initialize the
object.

Java constructor is invoked at the time of object creation. It constructs the


values i.e. provides data for the object that is why it is known as constructor.

Rules for creating java constructor


There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type

Types of java constructors


There are two types of constructors:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor that have no parameter is known as default
constructor.
Syntax of default constructor:
1. <class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It
will be invoked at the time of object creation.
1. class Bike1{
2. Bike1(){System.out.println("Bike is created");}
3. public static void main(String args[]){
4. Bike1 b=new Bike1();
5. }
6. }

Output:

Bike is created

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Rule: If there is no constructor in a class, compiler automatically creates a
default constructor.

Q) What is the purpose of default constructor?


Default constructor provides the default values to the object like 0, null etc.
depending on the type.

Example of default constructor that displays the default values


1. class Student3{
2. int id;
3. String name;
4.
5. void display(){System.out.println(id+" "+name);}
6.
7. public static void main(String args[]){
8. Student3 s1=new Student3();
9. Student3 s2=new Student3();
10. s1.display();
11. s2.display();
12. }
13. }

Output:

0 null
0 null

Explanation:In the above class,you are not creating any constructor so compiler
provides you a default constructor.Here 0 and null values are provided by
default constructor.

Java parameterized constructor


A constructor that have parameters is known as parameterized
constructor.
Why use parameterized constructor?
Parameterized constructor is used to provide different values to
the distinct objects.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Example of parameterized constructor
In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
1. class Student4{
2. int id;
3. String name;
4.
5. Student4(int i,String n){
6. id = i;
7. name = n;
8. }
9. void display(){System.out.println(id+" "+name);}
10.
11. public static void main(String args[]){
12. Student4 s1 = new Student4(111,"Karan");
13. Student4 s2 = new Student4(222,"Aryan");
14. s1.display();
15. s2.display();
16. }
17. }

Output:

111 Karan
222 Aryan

Constructor Overloading in Java:


Constructor overloading is a technique in Java in which a class can have any
number of constructors that differ in parameter lists.The compiler
differentiates these constructors by taking into account the number of
parameters in the list and their type.
Example of Constructor Overloading
1. class Student5{
2. int id;
3. String name;
4. int age;
5. Student5(int i,String n){
6. id = i;
7. name = n;
8. }
9. Student5(int i,String n,int a){
10. id = i;
11. name = n;
12. age=a;
13. }
14. void display(){System.out.println(id+" "+name+" "+age);}
15.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


16. public static void main(String args[]){
17. Student5 s1 = new Student5(111,"Karan");
18. Student5 s2 = new Student5(222,"Aryan",25);
19. s1.display();
20. s2.display();
21. }
22. }

Output:

111 Karan 0
222 Aryan 25

Difference between constructor and method in java


There are many differences between constructors and methods. They are given
below.

Java Constructor Java Method


Constructor is used to initialize the state of Method is used to expose
an object. behaviour of an object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default Method is not provided by
constructor if you don't have any constructor. compiler in any case.
Constructor name must be same as the class Method name may or may not be
name. same as class name.

Passing and Returning object form Method:


Pass object as perameter

Although Java is strictly pass by value, the precise effect differs between
whether a primitive type or a reference type is passed.

When we pass a primitive type to a method, it is passed by value. But when we


pass an object to a method, the situation changes dramatically, because objects
are passed by what is effectively call-by-reference. Java does this interesting
thing that’s sort of a hybrid between pass-by-value and pass-by-reference.
Basically, a parameter cannot be changed by the function, but the function can
ask the parameter to change itself via calling some method within it.

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

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


In Java we can pass objects to methods. For example, consider the following
program :

// Java program to demonstrate objects


// passing to methods.
class ObjectPassDemo
{
int a, b;

ObjectPassDemo(int i, int j)
{
a = i;
b = j;
}

// return true if o is equal to the invoking


// object notice an object is passed as an
// argument to method
boolean equalTo(ObjectPassDemo o)
{
return (o.a == a && o.b == b);
}
}

// Driver class
public class Test
{
public static void main(String args[])
{
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);

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


System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
}
}

Output:

ob1 == ob2: true


ob1 == ob3: false

Illustrative images for the above program

 Three objects ‘ob1’ , ‘ob2’ and ‘ob3’ are created:

ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);


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

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


 From the method side, a reference of type Foo with a name a is declared
and it’s initially assigned to null.

boolean equalTo(ObjectPassDemo o);

 As we call the method equalTo, the reference ‘o’ will be assigned to the
object which is passed as an argument, i.e. ‘o’ will refer to ‘ob2’ as
following statement execute.

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

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


 Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is
referring to ‘ob2’. Since values of ‘a’ and ‘b’ are same for both the
references, so if(condition) is true, so boolean true will be return.

if(o.a == a && o.b == b)

 Again ‘o’ will reassign to ‘ob3’ as the following statement execute.

System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));

 Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is


referring to ‘ob3’. Since values of ‘a’ and ‘b’ are not same for both the
references, so if(condition) is false, so else block will execute and
false will be return.

Defining a constructor that takes an object of its class as a parameter

One of the most common uses of object parameters involves constructors.


Frequently, in practice, there is need to construct a new object so that it is
initially the same as some existing object. To do this, either we can use

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Object.clone() method or define a constructor that takes an object of its class
as a parameter. The second option is illustrated in below example:

// Java program to demonstrate one object to


// initialize another
class Box
{
double width, height, depth;

// Notice this constructor. It takes an


// object of type Box. This constructor use
// one object to initialize another
Box(Box ob)
{
width = ob.width;
height = ob.height;
depth = ob.depth;
}

// constructor used when all dimensions


// specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}

// compute and return volume


double volume()
{
return width * height * depth;
}
}

// driver class
public class Test
{
public static void main(String args[])
{
// creating a box with all dimensions specified
Box mybox = new Box(10, 20, 15);

// creating a copy of mybox


Box myclone = new Box(mybox);

double vol;

// get volume of mybox


vol = mybox.volume();
System.out.println("Volume of mybox is " + vol);

// get volume of myclone


vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
}
}

Output:

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Volume of mybox is 3000.0
Volume of myclone is 3000.0

Returning Objects

In java, a method can return any type of data, including objects. For example,
in the following program, 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.

// Java program to demonstrate returning


// of objects
class ObjectReturnDemo
{
int a;

ObjectReturnDemo(int i)
{
a = i;
}

// This method returns an object


ObjectReturnDemo incrByTen()
{
ObjectReturnDemo temp =
new ObjectReturnDemo(a+10);
return temp;
}
}

// Driver class
public class Test
{
public static void main(String args[])
{
ObjectReturnDemo ob1 = new ObjectReturnDemo(2);
ObjectReturnDemo ob2;

ob2 = ob1.incrByTen();

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


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

Output:

ob1.a: 2
ob2.a: 12

Note : When an object reference is passed to a method, the reference itself is


passed by use of call-by-value. However, since the value being passed refers to
an object, the copy of that value will still refer to the same object that its
corresponding argument does. That’s why we said that java is strictly pass-by-
value.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Java "THIS" Keyword:
Keyword 'THIS' in Java is a reference variable that refers to the current
object.

The various usage of keyword Java 'THIS' in Java is as per the below,

 It can be used to refer current class instance variable


 It can be used to invoke or initiate current class constructor
 It can be passed as an argument in the method call
 It can be passed as argument in the constructor call
 It can be used to return the current class instance

Let's understand 'this' java keyword with an example.

Class: Let's create a class Account with

1. InstanceVariable: a and b and


2. Method Set data: To set the value for a and b.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


3. Method Show data: To display the values for a and b.
4. Main method: where we create an object for Account class and call methods
set data and show data.

Let's compile and run the code

Our expected output for A and B should be initialized to the values 2 and 3
respectively.

But the value is 0, Why? let's investigate.

In the method Set data, the arguments are declared as a and b, while the
instance variables are also named as a and b.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


During execution, the complier is confused. Whether "a" on the left side of the
assigned operator is the instance variable or the local variable. Hence, it is
not set the value of 'a' when the method set data is called.

So, problem can be overcome by "THIS" keyword

Append both 'a' and 'b' with the "this" keyword followed by a dot (.) operator.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


During code execution when an object calls the method 'setdata'. The keyword
'this' is replaced by the object handler "obj." (See the image below).

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


So now the compiler know,

 The 'a' on the left-hand side is an Instance variable.


 Whereas the 'a' on right-hand side is a local variable

The variables are initialized correctly, and the expected output is shown.

Summery of this kewword:

 It can be used to refer current class instance variable


 It can be used to invoke or initiate current class constructor
 It can be passed as an argument in the method call
 It can be passed as argument in the constructor call
 It can be used to return the current class instance

 Keyword 'THIS' in Java is a reference variable that refers to the current


object

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


To invoke current class method
You may 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. Let's see the example

1. class A{
2. void m(){System.out.println("hello m");}
3. void n(){
4. System.out.println("hello n");
5. //m();//same as this.m()
6. this.m();
7. }
8. }
9. class TestThis4{
10. public static void main(String args[]){
11. A a=new A();
12. a.n();
13. }}

Output:

hello n
hello m

this() : to invoke current class constructor(Constructor chaining)


The this() constructor call can be used to invoke the current class constructor.
It is used to reuse the constructor. In other words, it is used for constructor
chaining.

Calling default constructor from parameterized constructor:

1. class A{
2. A(){System.out.println("hello a");}
3. A(int x){

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


4. this();
5. System.out.println(x);
6. }
7. }
8. class TestThis5{
9. public static void main(String args[]){
10. A a=new A(10);
11. }}

Output:

hello a
10

Calling parameterized constructor from default constructor:

1. class A{
2. A(){
3. this(5);
4. System.out.println("hello a");
5. }
6. A(int x){
7. System.out.println(x);
8. }
9. }
10. class TestThis6{
11. public static void main(String args[]){
12. A a=new A();
13. }}

Output:

5
hello a

Real usage of this() constructor call(Application of this())


The this() constructor call should be used to reuse the constructor from the
constructor. It maintains the chain between the constructors i.e. it is used for
constructor chaining. Let's see the example given below that displays the actual
use of this keyword.

1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


10. Student(int rollno,String name,String course,float fee){
11. this(rollno,name,course);//reusing constructor
12. this.fee=fee;
13. }
14. void display(){System.out.println(rollno+" "+name+" "+course+" "+fee
);}
15. }
16. class TestThis7{
17. public static void main(String args[]){
18. Student s1=new Student(111,"ankit","java");
19. Student s2=new Student(112,"sumit","java",6000f);
20. s1.display();
21. s2.display();
22. }}

Output:

111 ankit java null


112 sumit java 6000

Rule: Call to this() must be the first statement in constructor.

this: to pass as an argument in the method


The this keyword can also be passed as an argument in the method. It is mainly
used in the event handling. Let's see the example:

1. class S2{
2. void m(S2 obj){
3. System.out.println("method is invoked");
4. }
5. void p(){
6. m(this);
7. }
8. public static void main(String args[]){
9. S2 s1 = new S2();
10. s1.p();
11. }
12. }

Output:

method is invoked

Application of this that can be passed as an argument:


In event handling (or) in a situation where we have to provide reference of a
class to another one. It is used to reuse one object in many methods.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


static keyword:
The static keyword is used in java mainly for memory management. It is used with
variables, methods, blocks and nested class. It is a keyword that are used for
share the same variable or method of a given class. This is used for a constant
variable or a method that is the same for every instance of a class. The main
method of a class is generally labeled static.

No object needs to be created to use static variable or call static methods,


just put the class name before the static variable or method to use them. Static
method can not call non-static method.

In java language static keyword can be used for following


 variable (also known as class variable)
 method (also known as class method)
 block
 nested class

Static variable
If any variable we declared as static is known as static variable.

 Static variable is used for fulfill the common requirement. For Example
company name of employees,college name of students etc. Name of the
college is common for all students.
 The static variable allocate memory only once in class area at the time of
class loading.

Advantage of static variable


Using static variable we make our program memory efficient (i.e it saves
memory).

When and why we use static variable


Suppose we want to store record of all employee of any company, in this case
employee id is unique for every employee but company name is common for all.
When we create a static variable as a company name then only once memory is
allocated otherwise it allocate a memory space each time for every employee.

Syntax for declare static variable:


public static variableName;

Syntax for declare static method:


public static void methodName()
{
.......
.......
}

Syntax for access static methods and static variable

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Syntax
className.variableName=10;
className.methodName();

Example
public static final double PI=3.1415;
public static void main(String args[])
{
......
......
}

Example of static variable.


In the below example College_Name is always same, and it is declared as static.

Example
class Student
{
int roll_no;
String name;
static String College_Name="ITM";
}
class StaticDemo
{
public static void main(String args[])
{
Student s1=new Student();
s1.roll_no=100;
s1.name="abcd";
System.out.println(s1.roll_no);
System.out.println(s1.name);
System.out.println(Student.College_Name);
Student s2=new Student();
s2.roll_no=200;
s2.name="zyx";
System.out.println(s2.roll_no);
System.out.println(s2.name);
System.out.println(Student.College_Name);
}
}

Example
Output:
100
abcd
ITM
200
zyx
ITM

In the above example College_Name variable is commonly sharable by both S1 and


S2 objects.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


In the above image static data variable are store in method are and non static
variable is store in java stack. Read more about this in JVM Architecture
chapter

why main method is static ?


Because object is not required to call static method if main() is non-static
method, then jvm create object first then call main() method due to that face
the problem of extra memory allocation.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


final keyword:
It is used to make a variable as a constant, Restrict method overriding,
Restrict inheritance. It is used at variable level, method level and class
level. In java language final keyword can be used in following way.

 Final at variable level


 Final at method level
 Final at class level

Final at variable level


Final keyword is used to make a variable as a constant. This is similar to const
in other language. A variable declared with the final keyword cannot be modified
by the program after initialization. This is useful to universal constants, such
as "PI".

Final Keyword in java Example


public class Circle
{
public static final double PI=3.14159;

public static void main(String[] args)


{
System.out.println(PI);
}
}

Final at method level


It makes a method final, meaning that sub classes can not override this method.
The compiler checks and gives an error if you try to override the method.

When we want to restrict overriding, then make a method as a final.

Example
public class A

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


{
public void fun1()
{
.......
}
public final void fun2()
{
.......
}

}
class B extends A
{
public void fun1()
{
.......
}
public void fun2()
{
// it gives an error because we can not override final method
}
}

Example of final keyword at method level

Example
class Employee
{
final void disp()
{
System.out.println("Hello Good Morning");
}
}
class Developer extends Employee
{
void disp()
{
System.out.println("How are you ?");
}
}
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
obj.disp();
}
}

Output
It gives an error

Final at class level


It makes a class final, meaning that the class can not be inheriting by other
classes. When we want to restrict inheritance then make class as a final.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Example
public final class A
{
......
......
}
public class B extends A
{
// it gives an error, because we can not inherit final class
}

Example of final keyword at class level

Example
final class Employee
{
int salary=10000;
}
class Developer extends Employee
{
void show()
{
System.out.println("Hello Good Morning");
}
}
class FinalDemo
{
public static void main(String args[])
{
Developer obj=new Developer();
Developer obj=new Developer();
obj.show();
}
}

Output
Output:
It gives an error

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Initialization block in JAVA
An initialization block is a block of code between braces that is executed
before the object of the class is created. As the execution of the
initialization block is dependent on the creation of the object we can easily
make a guess that it has two types of object.

1.Non static initialization block.


2.Static initialization block.

1. Non static initialization block.


It is dependent on the object and the initialization block is executed for each
object of the class that is created. It can initialize instance member variables
of the class. Here is a simple example.

class InitializationBlock
{
int[] arrVal = new int[10];
// Initialization block
{
System.out.println("In initialization block\n");
for(int i=0; i<arrVal.length; i++)
{
arrVal[i] = (int)(100.0*Math.random());
}
}

void Display()
{
System.out.println("Start display\n");
for(int i=0; i<arrVal.length; i++)
{
System.out.println(" " + arrVal[i]);
}
System.out.println("End display\n");
}

public static void main(String[] args)


{
InitializationBlock ib1 = new InitializationBlock();
System.out.println("First object is created");
ib1.Display();

InitializationBlock ib2 = new InitializationBlock();


System.out.println("Second object is created");
ib2.Display();
}
}

2. Static initialization block.


It is defined using the keyword static and is executed once when the class is
loaded and has a restriction that it can only initialize static data members of
the class.
class InitializationBlock
{
static int[] arrVal = new int[10];
// Initialization block
static
{

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


System.out.println("In initialization block\n");
for(int i=0; i<arrVal.length; i++)
{
arrVal[i] = (int)(100.0*Math.random());
}
}

void Display()
{
System.out.println("Start display\n");
for(int i=0; i<arrVal.length; i++)
{
System.out.println(" " + arrVal[i]);
}
System.out.println("End display\n");
}

public static void main(String[] args)


{
InitializationBlock ib1 = new InitializationBlock();
System.out.println("First object is created");
ib1.Display();

InitializationBlock ib2 = new InitializationBlock();


System.out.println("Second object is created");
ib2.Display();
}
}

The only difference between both the samples above is with the two static
keywords added and you can definitely see difference in the output. One outputs
different values for two objects created and other one the same values.

You can have multiple initialization blocks in a class in which case they
execute in the sequence in which they appear in the class.

Note that any initialization block present in the class is executed before the
constructor.

So now the question comes why we need constructors if we have initialization


blocks. The answer is we don't need the default constructor but initialization
block cannot be parameterized and so you cannot have objects taking values from
out side and so initialization block is not a substitute for constructor.

Access Modifier:
Java provides a number of access modifiers to set access levels for classes,
variables, methods, and constructors. The four access levels are −

 Visible to the package, the default. No modifiers are needed.


 Visible to the class only (private).
 Visible to the world (public).
 Visible to the package and all subclasses (protected).

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Default Access Modifier - No Keyword
Default access modifier means we do not explicitly declare an access modifier
for a class, field, method, etc.

A variable or method declared without any access control modifier is available


to any other class in the same package. The fields in an interface are
implicitly public static final and the methods in an interface are by default
public.

Example
Variables and methods can be declared without any modifiers, as in the following
examples −

String version = "1.5.1";

boolean processOrder() {
return true;
}

Private Access Modifier - Private


Methods, variables, and constructors that are declared private can only be
accessed within the declared class itself.

Private access modifier is the most restrictive access level. Class and
interfaces cannot be private.

Variables that are declared private can be accessed outside the class, if public
getter methods are present in the class.

Using the private modifier is the main way that an object encapsulates itself
and hides data from the outside world.

Example
The following class uses private access control −

public class Logger {


private String format;

public String getFormat() {


return this.format;
}

public void setFormat(String format) {


this.format = format;
}
}

Here, the format variable of the Logger class is private, so there's no way for
other classes to retrieve or set its value directly.

So, to make this variable available to the outside world, we defined two public
methods: getFormat(), which returns the value of format, and setFormat(String),
which sets its value.

Public Access Modifier - Public


A class, method, constructor, interface, etc. declared public can be accessed

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


from any other class. Therefore, fields, methods, blocks declared inside a
public class can be accessed from any class belonging to the Java Universe.

However, if the public class we are trying to access is in a different package,


then the public class still needs to be imported. Because of class inheritance,
all public methods and variables of a class are inherited by its subclasses.

Example
The following function uses public access control −

public static void main(String[] arguments) {


// ...
}

The main() method of an application has to be public. Otherwise, it could not be


called by a Java interpreter (such as java) to run the class.

Protected Access Modifier - Protected


Variables, methods, and constructors, which are declared protected in a
superclass can be accessed only by the subclasses in other package or any class
within the package of the protected members' class.

The protected access modifier cannot be applied to class and interfaces.


Methods, fields can be declared protected, however methods and fields in a
interface cannot be declared protected.

Protected access gives the subclass a chance to use the helper method or
variable, while preventing a nonrelated class from trying to use it.

Example
The following parent class uses protected access control, to allow its child
class override openSpeaker() method −

class AudioPlayer {
protected boolean openSpeaker(Speaker sp) {
// implementation details
}
}

class StreamingAudioPlayer {
boolean openSpeaker(Speaker sp) {
// implementation details
}
}

Here, if we define openSpeaker() method as private, then it would not be


accessible from any other class other than AudioPlayer. If we define it as
public, then it would become accessible to all the outside world. But our
intention is to expose this method to its subclass only, that’s why we have used
protected modifier.

Access Control and Inheritance


The following rules for inherited methods are enforced −

 Methods declared public in a superclass also must be public in all


subclasses.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


 Methods declared protected in a superclass must either be protected or
public in subclasses; they cannot be private.

 Methods declared private are not inherited at all, so there is no rule for
them.

Inner class in java


Inner class means one class which is a member of another class. There are
basically four types of inner classes in java.

1) Nested Inner class


2) Method Local inner classes
3) Anonymous inner classes
4) Static nested classes

Nested Inner class can access any private instance variable of outer class. Like
any other instance variable, we can have access modifier private, protected,
public and default modifier.
Like class, interface can also be nested and can have access specifiers.

Following example demonstrates a nested class.

class Outer {
// Simple nested inner class
class Inner {
public void show() {
System.out.println("In a nested class method");
}
}
}
class Main {
public static void main(String[] args) {
Outer.Inner in = new Outer().new Inner();
in.show();
}
}

Output:

In a nested class method

As a side note, we can’t have static method in a nested inner class because an
inner class is implicitly associated with an object of its outer class so it
cannot define any static method for itself. For example the following program
doesn’t compile.

class Outer {
void outerMethod() {
System.out.println("inside outerMethod");
}
class Inner {
public static void main(String[] args){
System.out.println("inside inner class Method");
}

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


}
}

Output:

Error illegal static declaration in inner class


Outer.Inner public static void main(String[] args)
modifier ‘static’ is only allowed in constant
variable declaration

An interface can also be nested and nested interfaces have some interesting
properties. We will be covering nested interfaces in the next post.

Method Local inner classes


Inner class can be declared within a method of an outer class. In the following
example, Inner is an inner class in outerMethod().

class Outer {
void outerMethod() {
System.out.println("inside outerMethod");
// Inner class is local to outerMethod()
class Inner {
void innerMethod() {
System.out.println("inside innerMethod");
}
}
Inner y = new Inner();
y.innerMethod();
}
}
class MethodDemo {
public static void main(String[] args) {
Outer x = new Outer();
x.outerMethod();
}
}

Output

Inside outerMethod
Inside innerMethod

Method Local inner classes can’t use local variable of outer method until that
local variable is not declared as final. For example, the following code
generates compiler error (Note that x is not final in outerMethod() and
innerMethod() tries to access it)

class Outer {
void outerMethod() {
int x = 98;
System.out.println("inside outerMethod");
class Inner {
void innerMethod() {
System.out.println("x= "+x);

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


}
}
Inner y = new Inner();
y.innerMethod();
}
}
class MethodLocalVariableDemo {
public static void main(String[] args) {
Outer x=new Outer();
x.outerMethod();
}
}

Output:

local variable x is accessed from within inner class;


needs to be declared final

But the following code compiles and runs fine (Note that x is final this time)

class Outer {
void outerMethod() {
final int x=98;
System.out.println("inside outerMethod");
class Inner {
void innerMethod() {
System.out.println("x = "+x);
}
}
Inner y = new Inner();
y.innerMethod();
}
}
class MethodLocalVariableDemo {
public static void main(String[] args){
Outer x = new Outer();
x.outerMethod();
}
}

Output-:

Inside outerMethod
X = 98

The main reason we need to declare a local variable as a final is that local
variable lives on stack till method is on the stack but there might be a case
the object of inner class still lives on the heap.
Method local inner class can’t be marked as private, protected, static and
transient but can be marked as abstract and final, but not both at the same
time.

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


Static nested classes
Static nested classes are not technically an inner class. They are like a static
member of outer class.
System.out.println("inside outerMethod");
}

// A static inner class


static class Inner {
public static void main(String[] args) {
System.out.println("inside inner class Method");
outerMethod();
}
}

Output

inside inner class Method


inside outerMethod

Anonymous inner classes


Anonymous inner classes are declared without any name at all. They are created
in two ways.
a) As subclass of specified type

class Demo {
void show() {
System.out.println("i am in show method of super class");
}
}
class Flavor1Demo {

// An anonymous class with Demo as base class


static Demo d = new Demo() {
void show() {
super.show();
System.out.println("i am in Flavor1Demo class");
}
};
public static void main(String[] args){
d.show();
}
}

Output

i am in show method of super class


i am in Flavor1Demo class

In the above code, we have two class Demo and Flavor1Demo. Here demo act as
super class and anonymous class acts as a subclass, both classes have a method
show(). In anonymous class show() method is overridden.

a) As implementer of the specified interface

Pradeep Laxkar , ITM Universe Vadodara (8140540626 , pradeep.laxkar@gmail.com)


class Flavor2Demo {

// An anonymous class that implements Hello interface


static Hello h = new Hello() {
public void show() {
System.out.println("i am in anonymous class");
}
};

public static void main(String[] args) {


h.show();
}
}

interface Hello {
void show();
}

Output:

i am in anonymous class

Garbage Collection in Java

• In C/C++, programmer is responsible for both creation and destruction of


objects. Usually programmer neglects destruction of useless objects. Due
to this negligence, at certain point, for creation of new objects,
sufficient memory may not be available and entire program will terminate
abnormally causing OutOfMemoryErrors.
• But in Java, the programmer need not to care for all those objects which
are no longer in use. Garbage collector destroys these objects.
• Garbage collector is best example of Daemon thread as it is always running
in background.
• Main objective of Garbage Collector is to free heap memory by destroying
unreachable objects.

Important terms :

1. Unreachable objects : An object is said to be unreachable iff it doesn’t


contain any reference to it. Also note that objects which are part of
island of isolation are also unreachable.

Integer i = new Integer(4);


// the new Integer object is reachable via the reference in 'i'
i = null;
// the Integer object is no longer reachable.
2. Eligibility for garbage collection : An object is said to be eligible for
GC(garbage collection) iff it is unreachable. In above image, after i =
null; integer object 4 in heap area is eligible for garbage collection.

Ways to make an object eligible for GC

• Even though programmer is not responsible to destroy useless objects but


it is highly recommended to make an object unreachable(thus eligible for
GC) if it is no longer required.
• There are generally four different ways to make an object eligible for
garbage collection.
1. Nullifying the reference variable
2. Re-assigning the reference variable
3. Object created inside method
4. Island of Isolation
All above ways with examples are discussed in separate article : How to
make object eligible for garbage collection

Ways for requesting JVM to run Garbage Collector

• Once we made object eligible for garbage collection, it may not destroy
immediately by garbage collector. Whenever JVM runs Garbage Collector
program, then only object will be destroyed. But when JVM runs Garbage
Collector, we can not expect.
• We can also request JVM to run Garbage Collector. There are two ways to do
it :
1. Using System.gc() method : System class contain static method
gc() for requesting JVM to run Garbage Collector.
2. Using Runtime.getRuntime().gc() method : Runtime class allows
the application to interface with the JVM in which the
application is running. Hence by using its gc() method, we can
request JVM to run Garbage Collector.
// Java program to demonstrate requesting
// JVM to run Garbage Collector
public class Test
{
public static void main(String[] args)
InterruptedException
{
Test t1 = new Test();
Test t2 = new Test();

// Nullifying the reference variable


t1 = null;

// requesting JVM for running Garbage Collector


System.gc();

// Nullifying the reference variable


t2 = null;

// requesting JVM for running Garbage Collector


Runtime.getRuntime().gc();

@Override
// finalize method is called on object once
// before garbage collecting it
protected void finalize()
{
System.out.println("Garbage collector called");
System.out.println("Object garbage collected : " +
this);
}
}
Output:

Garbage collector called


Object garbage collected : Test@46d08f12
Garbage collector called
Object garbage collected : Test@481779b8

Note :

1. There is no guarantee that any one of above two methods will


definitely run Garbage Collector.
2. The call System.gc() is effectively equivalent to the call :
Runtime.getRuntime().gc()

Finalization
• Just before destroying an object, Garbage Collector calls finalize()
method on the object to perform cleanup activities. Once finalize() method
completes, Garbage Collector destroys that object.
• finalize() method is present in Object class with following prototype.
protected void finalize() throws Throwable

Based on our requirement, we can override finalize() method for perform


our cleanup activities like closing connection from database.

Note :

1. The finalize() method called by Garbage Collector not JVM. Although


Garbage Collector is one of the module of JVM.
2. Object class finalize() method has empty implementation, thus it is
recommended to override finalize() method to dispose of system
resources or to perform other cleanup.
3. The finalize() method is never invoked more than once for any given
object.
4. If an uncaught exception is thrown by the finalize() method, the
exception is ignored and finalization of that object terminates.

Notes of abstract class is at the end of UNIT-4.


References:

1. Programming with Java A Primer – E.Balaguruswamy,Mc Grawhill

2. The Complete Reference, Java 2 (Fourth Edition),Herbert Schild, - TMH.

3. http://www.javacjava.com/tutorials.aspx

4. https://www.javatpoint.com/java-tutorial

5. https://way2java.com/java-lang/

6. https://www.tutorialspoint.com/java/

7. www.studytonight.com/java/

8. https://beginnersbook.com/2013/05/

9. www1.fs.cvut.cz/cz/u12110/prt/java/

10.A Programmer’s Guide to Java TM SCJP Certification A Comprehensive Primer-


Khalid A. Mughal , Rolf W. Rasmussen.

11. https://www.guru99.com/

12. www.c4learn.com/java/

13. www.geeksforgeeks.org/

14. www.sitesbay.com/java/

15.https://www.go4expert.com/articles/initialization-block-java-t1254/

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