0% found this document useful (0 votes)
0 views34 pages

Notes 24CS202 OOP Through Java Unit II Chapter 1 Introduction to Classes and Objects

Uploaded by

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

Notes 24CS202 OOP Through Java Unit II Chapter 1 Introduction to Classes and Objects

Uploaded by

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

24CS202 – OOP Through Java

UNIT II
Chapter 1: Classes and Objects
4.1 Class Fundamentals

4.1.1 What Is a Class?

Class is the logical unit upon which the entire java language is built because it defines the
shape and nature of an object. “User defined Data type”, “Definition”, “Blue print”, “Template”
and “Prototype” that defines and describe about all objects that are same kind.

Classes create objects and objects use methods to communicate between them. They
provide a convenient method for packaging a group of logically related data items and functions
that work on them. Class essentially serves as a template for an object and behaves like a basic
data type “int”.

In the real world, you'll often find many individual objects all of the same kind. There may
be thousands of other bicycles in existence, all of the same make and model. Each bicycle was
built from the same set of blueprints and therefore contains the same components. In object-
oriented terms, we say that your bicycle is an instance of the class of objects known as bicycles.
A class is the blueprint from which individual objects are created.

Java class is nothing but a template for object you are going to create or it’s a blue print
by using this we create an object. In simple word we can say it’s a specification or a pattern which
we define and every object we define will follow that pattern.

4.1.2 What does Java Class consist of?

• When we create class in java the first step is keyword class and then name of the class or
identifier we can say.
• Next is class body which starts with curly braces {} and between this all things related with
that class means their property and method will come here.

Mr.Raghu Virapratap
1
Asst. Professor
CSE Dept, V.R.S.E.C
4.1.3 What are the members of Class:

When we create a class its totally incomplete without defining any member of this class same
like we can understand one family is incomplete if they have no members.

Field:

Field is nothing but the property of the class or object which we are going to create .for
example if we are creating a class called computer then they have property like model,
mem_size, hd_size, os_type etc.

Method :

Method is nothing but the operation that an object can perform it define the behavior of object
how an object can interact with outside world .startMethod (), shutdownMethod(). Access
Level of members: Access level is nothing but where we can use that members of the class.
Each field and method has an access level:

• private: accessible only in this class


• package or default: accessible only in this package
• protected: accessible only in this package and in all subclasses of this class
• public: accessible everywhere this class is available
The general form of a class definition is shown here:

Syntax:

class classname {

type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;

type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method

Mr.Raghu Virapratap
2
Asst. Professor
CSE Dept, V.R.S.E.C
}
}

The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class are
called members of the class. In most classes, the instance variables are acted upon and accessed
by the methods defined for that class. Thus, it is the methods that determine how a class’ data
can be used.

As stated earlier, each object has its own copies of the instance variables. This means
that if you have two Box objects, each has its own copy of depth, width, and height. It is
important to understand that changes to the instance variables of one object have no effect on
the instance variables of another.

Example :

// This program declares two Box objects.

class Box
{
double width;
double height;
double depth;
}

class BoxDemo2 {
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;

Mr.Raghu Virapratap
3
Asst. Professor
CSE Dept, V.R.S.E.C
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}

You should call the file that contains this program BoxDemo.java, because the main( ) method is
in the class called BoxDemo, not the class called Box. When you compile this program, you will
find that two .class files have been created, one for Box and one for BoxDemo. The Java
compiler automatically puts each class into its own .class file. It is not necessary for both the
Box and the BoxDemo class to actually be in the same source file. You could put each class in its
own file, called Box.java and BoxDemo.java, respectively. To run this program, you must
execute BoxDemo.class. When you do, you will see the following output: Volume is 3000.0

4.2 What is an Object

Objects are the basic run time entity or in other words object is an instance of a class. An
object is a software bundle of variables and related methods of the special class. In real-world
objects share two characteristics: They have all state and behavior. For example, The squares
have state such as : sides and behaviors such as its areas and perimeters. Rectangles have state
such as: length, breadth and behavior such as its areas and perimeters. A object implements its
behavior with methods of it's classes. A method is a function (subroutine) associated with an
object.

i) Creating Objects

As you know, a class provides the blueprint for objects; you create an object from a class. Each
of the following statements taken from the BoxDemo program creates an object and assigns it
to a variable:

Box mybox1= new Box( );

The first line creates an object of the Box class

Each of these statements has three parts (discussed in detail below):

1. Declaration: The code set in bold are all variable declarations that associate a variable
name with an object type.

Mr.Raghu Virapratap
4
Asst. Professor
CSE Dept, V.R.S.E.C
2. Instantiation: The new keyword is a Java operator that creates the object.
3. Initialization: The new operator is followed by a call to a constructor, which initializes
the new object.

ii) Declaring a Variable to Refer to an Object

Previously, you learned that to declare a variable, you write:

type name;

This notifies the compiler that you will use name to refer to data whose type is type.
With a primitive variable, this declaration also reserves the proper amount of memory for the
variable.

You can also declare a reference variable on its own line. For example:

Box mybox1;

If you declare myBox1 like this, its value will be undetermined until an object is actually
created and assigned to it. Simply declaring a reference variable does not create an object. For
that, you need to use the new operator, as described in the next section. You must assign an
object to myBox1 before you use it in your code. Otherwise, you will get a compiler error.

A variable in this state, which currently references no object, can be illustrated as follows (the
variable name, myBox1, plus a reference pointing to nothing):

iii) Instantiating a Class

The new operator instantiates a class by allocating memory for a new object and
returning a reference to that memory. The new operator also invokes the object constructor.

Note: The phrase "instantiating a class" means the same thing as "creating an object." When
you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

The new operator requires a single, postfix argument: a call to a constructor. The name
of the constructor provides the name of the class to instantiate.

The new operator returns a reference to the object it created. This reference is usually
assigned to a variable of the appropriate type, like:

Box myBox1 = new Box( );


Mr.Raghu Virapratap
5
Asst. Professor
CSE Dept, V.R.S.E.C
The reference returned by the new operator does not have to be assigned to a variable.
It can also be used directly in an expression. For example:

double width = new Box().width;

This statement will be discussed in the next section.

iv) Initializing an Object

Here's the code for the Box class:

class Box
{
double width;
double height;
double depth;
// Constructor call

public Box( )
{
width=0.0;
height=0.0;
depth=0.0;
}
}

This class contains a single constructor. You can recognize a constructor because its declaration
uses the same name as the class and it has no return type. The constructor in the Box class
initializes default values to instance variables.

4.3 Defining Methods as a member of a class

Here is an example of a typical method declaration:

public double volume(double width, double height, double depth)

//do the calculation here

The only required elements of a method declaration are the method's return type,
name, a pair of parentheses, (), and a body between braces, {}.
Mr.Raghu Virapratap
6
Asst. Professor
CSE Dept, V.R.S.E.C
More generally, method declarations have six components, in order:

• Modifiers—such as public, private, and others you will learn about later.
• The return type—the data type of the value returned by the method, or void if the
method does not return a value.
• The method name—the rules for field names apply to method names as well, but the
convention is a little different.
• The parameter list in parenthesis—a comma-delimited list of input parameters,
preceded by their data types, enclosed by parentheses, (). If there are no parameters,
you must use empty parentheses.
• An exception list—to be discussed later.
• The method body, enclosed between braces—the method's code, including the
declaration of local variables, goes here.

Modifiers return types, and parameters will be discussed later in this lesson. Exceptions
are discussed in a later lesson.

Definition: Two of the components of a method declaration comprise the method


signature—the method's name and the parameter types.

The signature of the method declared above is:

double volume(double, double, double)

Naming a Method

Although a method name can be any legal identifier, code conventions restrict
method names. By convention, method names should be a verb in lowercase or a multi-word
name that begins with a verb in lowercase, followed by adjectives, nouns, etc. In multi-word
names, the first letter of each of the second and following words should be capitalized. Here
are some examples:

run
runFast
getBackground
getFinalData
compareTo
setX
isEmpty

Typically, a method has a unique name within its class. However, a method
might have the same name as other methods due to method overloading.

Mr.Raghu Virapratap
7
Asst. Professor
CSE Dept, V.R.S.E.C
4.4 Using Objects

Once you've created an object, you probably want to use it for something. You may need to use
the value of one of its fields, change one of its fields, or call one of its methods to perform an
action.

i) Referencing an Object's Fields

Object fields are accessed by their name. You must use a name that is unambiguous.

You may use a simple name for a field within its own class. For example, we can add a
statement within the Box class that prints the width and height:

System.out.println("Width and height are: " + width + ", " + height);

In this case, width and height are simple names.

Code that is outside the object's class must use an object reference or expression,
followed by the dot (.) operator, followed by a simple field name, as in:

objectReference.fieldName

For example

Consider the following Program


// This program declares two Box objects.

class Box
{
double width;
double height;
double depth;

Box()
{
width=0.0;
height=0.0;
depth=0.0;
}

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

Mr.Raghu Virapratap
8
Asst. Professor
CSE Dept, V.R.S.E.C
}

class BoxDemo
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;

// assign values to mybox1's instance variables


mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;

/* assign different values to mybox2's instance variables */


mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;

// compute volume of first box


vol = mybox1.width * mybox1.height * mybox1.depth;

System.out.println("Volume is " + vol);

// compute volume of second box


System.out.println("Volume is " + mybox2.volume( ););
}
}

The code in the BoxDemo class is outside the code for the Box class. So to refer to
the depth , width , and height fields within the Box object named myBox1,
the BoxDemo class must use the names myBox1.depth, myBox1.width,
and myBox1.height, respectively. The program uses two of these names to display
the width and the height of myBox1

System.out.println("Width of myBox1 " + myBox1.width);


System.out.println("Height of myBox1 " + myBox1.height);

Attempting to use the simple names width and height from the code in
the BoxDemo class doesn't make sense — those fields exist only within an object — and results
in a compiler error.

Mr.Raghu Virapratap
9
Asst. Professor
CSE Dept, V.R.S.E.C
Later, the program uses similar code to display information about myBox2. Objects of the
same type have their own copy of the same instance fields. Thus, each Rectangle object has fields
named depth, width, and height. When you access an instance field through an object reference,
you reference that particular object's field. The two objects myBox1 and myBox2 in
the BoxDemo program have different depth, width, and height fields.

To access a field, you can use a named reference to an object, as in the previous examples,
or you can use any expression that returns an object reference. Recall that the new operator
returns a reference to an object. So you could use the value returned from new to access a new
object's fields:

double height = new Box().height;

This statement creates a new Box object and immediately gets its height. In essence, the
statement calculates the default height of a Box. Note that after this statement has been
executed, the program no longer has a reference to the created Box, because the program never
stored the reference anywhere. The object is unreferenced, and its resources are free to be
recycled by the Java Virtual Machine.

ii) Calling an Object's Methods

You also use an object reference to invoke an object's method. You append the method's
simple name to the object reference, with an intervening dot operator (.). Also, you provide,
within enclosing parentheses, any arguments to the method. If the method does not require any
arguments, use empty parentheses.

objectReference.methodName(argumentList);

or:

objectReference.methodName();

The Box class has a method: volume() to compute the Box's volume. Here's
the BoxDemo code that invokes a method volume() :

System.out.println("Volume of myBox2 " + myBox2.volume());

The statement invokes volume( ) of myBox2 .

As with instance fields, objectReference must be a reference to an object. You can use a
variable name, but you also can use any expression that returns an object reference.

The new operator returns an object reference, so you can use the value returned from
new to invoke a new object's methods:

Mr.Raghu Virapratap
10
Asst. Professor
CSE Dept, V.R.S.E.C
4.4 Accessing Instance Variables and Methods:

Instance variables and methods are accessed via created objects. To access an instance variable
the fully qualified path should be as follows:

/* First create an object */


ObjectReference = new Constructor();

/* 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("Passed Name 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( );

Mr.Raghu Virapratap
11
Asst. Professor
CSE Dept, V.R.S.E.C
/* 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 would produce following result:

Passed Name is :tommy


Puppy's age is :2
Variable Value :2

4.5 Constructors

Constructor is a special type of method that is used to initialize the state of an object. Constructor
is invoked at the time of object creation. It constructs the values i.e. data for the object that is
why it is known as constructor.

Constructor is just like the instance method but it does not have any explicit return type.

A java constructor has the same name as the name of the class to which it belongs.
Constructor’s syntax does not include a return type, since constructors never return a value.

Constructors may include parameters of various types. When the constructor is invoked
using the new operator, the types must match those that are specified in the constructor
definition.

Java provides a default constructor which takes no arguments and performs no special
actions or initializations, when no explicit constructors are provided.

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.

Example of a constructor is given below:

public class Box{


public Box()
{
}

Mr.Raghu Virapratap
12
Asst. Professor
CSE Dept, V.R.S.E.C
public Box(double width)
{
// This constructor has one parameter, name.
}
}

Rules for Constructor

1. Constructors can use any access modifier, including private. (A private constructor means
only code within the class itself cans instantiate an object of that type, so if
the private constructor class wants to allow an instance of the class to be used, the class
must provide a static method or variable that allows access to an instance created from
within the class.)
2. The constructor name must match the name of the class.
3. Constructors must not have a return type.
4. It’s legal (but stupid) to have a method with the same name as the class, but that doesn’t
make it a constructor. If you see a return type, it’s a method rather than a constructor. In
fact, you could have both a method and a constructor with the same name the name of the
class in the same class, and that’s not a problem for Java. Be careful not to mistake a
method for a constructor, be sure to look for a return type.
5. If you don’t type a constructor into your class code, a default constructor will be
automatically generated by the compiler.
6. The default constructor is ALWAYS a no-arg constructor.
7. If you want a no-arg constructor and you’ve typed any other constructor(s) into your class
code, the compiler won’t provide the no-arg constructor for you. In other words, if you’ve
typed in a constructor with arguments, you won’t have a no-arg constructor unless you
type it in yourself !
8. Every constructor has, as its first statement, either a call to an overloaded constructor
(this()) or a call to the superclass constructor (super()), although remember that this call
can be inserted by the compiler.
9. If you do type in a constructor (as opposed to relying on the compiler-generated default
constructor), and you do not type in the call to super() or a call to this(), the compiler will
insert a no-arg call to super() for you, as the very first statement in the constructor.
10. A call to super() can be either a no-arg call or can include arguments passed to the super
constructor.
11. A no-arg constructor is not necessarily the default (i.e., compiler-supplied) constructor,
although the default constructor is always a no-arg constructor. The default constructor is
the one the compiler provides! While the default constructor is always a no-arg
constructor, you’re free to put in your own noarg constructor.
12. You cannot make a call to an instance method, or access an instance variable, until after
the super constructor runs.

Mr.Raghu Virapratap
13
Asst. Professor
CSE Dept, V.R.S.E.C
13. Only static variables and methods can be accessed as part of the call to super() or this().
(Example: super(Animal.NAME) is OK, because NAME is declared as a static variable.)
14. Abstract classes have constructors, and those constructors are always called when a
concrete subclass is instantiated.
15. Interfaces do not have constructors. Interfaces are not part of an object’s inheritance tree.
16. The only way a constructor can be invoked is from within another constructor

Types of Constructors

There are two types of constructors:


1. default constructor (no-arg constructor)
2. parameterized constructor

1) Default Constructor

A constructor that has no parameter is known as default constructor.

Syntax of default constructor:

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

//example of default constructor

Mr.Raghu Virapratap
14
Asst. Professor
CSE Dept, V.R.S.E.C
class Box{
Box(){
System.out.println("Box is created");
}

public static void main(String args[]){


Box b=new Box();
}
}
Output: Box is created

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

What is the purpose of default constructor?

Default constructor provides the default values to the object.

Example of default constructor that displays the default values

//example of default values provided by constructor

class Box {
double width;
double height;
double depth;

void volume() {
System.out.print("volume is");
System.out.println(width * height * depth);
}
}

class Boxdemo
{
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
mybox1.volume();
mybox2.volume();
}
}
Output:

0.0

Mr.Raghu Virapratap
15
Asst. Professor
CSE Dept, V.R.S.E.C
0.0

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.

Parameterized constructor

A constructor that has parameter is known as parameterized constructor.

Why use parameterized constructor?

Parameterized constructor is used to provide different values to the distinct objects.

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.

class Box {
double width;
double height;
double depth;

// This is the constructor for Box.


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

// compute and return volume


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

class BoxDemo {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);

double vol;

// get volume of first box

Mr.Raghu Virapratap
16
Asst. Professor
CSE Dept, V.R.S.E.C
vol = mybox1.volume();
System.out.println("Volume is " + vol);

// get volume of second box


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

Constructor Overloading

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

//Program of constructor overloading

In addition to overloading normal methods, you can also overload constructor


methods. In fact, for most real-world classes that you create, overloaded constructors will
be the norm, not the exception. To understand why, we can take example for this below
program.
class Box {
double width;
double height;
double depth;
Box ( double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
As you can see, the Box() constructor requires three parameters. This means that all
declarations of Box objects must pass three arguments to the Box() constructor. For
example, the following statement is currently invalid:
Box ob = new Box();
Since Box() requires three arguments, it’s an error to call it without them. This raises
some important questions. What if you simply wanted a box and did not care ( or know)
what its initial dimensions were? Or, what if you want to be able to initialize a cube by

Mr.Raghu Virapratap
17
Asst. Professor
CSE Dept, V.R.S.E.C
specifying only one value that would be used for all three dimensions? As the Box class is
currently written, these other options are not available to you.
Fortunately, the solution to these problems is quite easy: simply overload
the Box constructor so that it handles the situations just described. Here is a program that
contains an improved version of Box that does just that:
class Box{
double width;
double height;
double depth;

Box ( double w, double h, double d) {


width = w;
height = h;
depth = d;
}
Box() {
width = -1;
height = -1;
depth = -1;
}
Box (double len) {
width = height = depth = len;
}
double volume() {
return width * height * depth;
}
}
class OverloadCons {
public static void main (String args[]) {
Box mybox1 = new Box(10, 20,15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println(“Volume of mybox1 is” + vol);
vol = mybox2.volume();
System.out.println(“Volume of mybox2 is” + vol);
vol = mycube.volume();
System.out.println(“Volume of mycube is” + vol);
The output produced by this program is shown here:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mybox1 is 343.0

Mr.Raghu Virapratap
18
Asst. Professor
CSE Dept, V.R.S.E.C
As you can see, the proper overloaded constructor is called based
upon the parameters specified when new is executed.

Copy Constructors’

Copying the values of one object to another like copy constructor in C++
There are many ways to copy the values of one object into another.
They are:
• By constructor
• By assigning the values of one object into another
• By clone() method of Object class
In this example, we are going to copy the values of one object into another using constructor.

//Program of Copying the values of one object to another

class Box {
double width;
double height;
double depth;

// This is the constructor for Box.


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

// compute and return volume


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

class BoxDemo {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(mybox1);

double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume is " + vol);
Mr.Raghu Virapratap
19
Asst. Professor
CSE Dept, V.R.S.E.C
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

Copying the values of one object to another without constructor


We can copy the values of one object into another by assigning the objects values to another
object. In this case, there is no need to create the constructor.

4.6. Using “this” Keyword in Java

There can be a lot of usage of this keyword. In java, this is a reference variable that refers
to the current object.

Usage of this keyword

1. this keyword can be used to refer current class instance variable.


2. this() can be used to invoke current class constructor.

Within an instance method or a constructor, this is a reference to the current object — the
object whose method or constructor is being called. You can refer to any member of the
current object from within an instance method or a constructor by using this.

Using this with a Field

The most common reason for using the keyword is because a field is shadowed by a method or
constructor parameter.

For example, the Box class was written like this

public class Point {


Mr.Raghu Virapratap
20
Asst. Professor
CSE Dept, V.R.S.E.C
public int x = 0;
public int y = 0;

//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}

But it could have been written like this:

public class Point {


public int x = 0;
public int y = 0;

//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}

Each argument to the constructor shadows one of the object's fields — inside the
constructor x is a local copy of the constructor's first argument. To refer to the Point field x, the
constructor must use this.x.

Using this with a Constructor

From within a constructor, you can also use the this keyword to call another constructor in the
same class. Doing so is called an explicit constructor invocation. Here's another Rectangle class,
with a different implementation from the one in the Objects section.

public class Rectangle {


private int x, y;
private int width, height;

public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {

Mr.Raghu Virapratap
21
Asst. Professor
CSE Dept, V.R.S.E.C
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
...
}

This class contains a set of constructors. Each constructor initializes some or all of the rectangle's
member variables. The constructors provide a default value for any member variable whose
initial value is not provided by an argument. For example, the no-argument constructor calls the
four-argument constructor with four 0 values and the two-argument constructor calls the four-
argument constructor with two 0 values. As before, the compiler determines which constructor
to call, based on the number and the type of arguments.If present, the invocation of another
constructor must be the first line in the constructor.

4.7 The Garbage Collection

Some object-oriented languages require that you keep track of all the objects you create
and that you explicitly destroy them when they are no longer needed. Managing memory
explicitly is tedious and error-prone. The Java platform allows you to create as many objects as
you want (limited, of course, by what your system can handle), and you don't have to worry about
destroying them. The Java runtime environment deletes objects when it determines that they
are no longer being used. This process is called garbage collection.

An object is eligible for garbage collection when there are no more references to that
object. References that are held in a variable are usually dropped when the variable goes out of
scope. Or, you can explicitly drop an object reference by setting the variable to the special
value null. Remember that a program can have multiple references to the same object; all
references to an object must be dropped before the object is eligible for garbage collection.

The Java runtime environment has a garbage collector that periodically frees the memory
used by objects that are no longer referenced. The garbage collector does its job automatically
when it determines that the time is right.

In java, garbage means unreferenced objects. Garbage Collection is process of reclaiming


the runtime unused memory automatically. In other words, it is a way to destroy the unused
objects.

To do so, we were using free () function in C language and delete () in C++. But, in java it
is performed automatically. So, java provides better memory management.

Mr.Raghu Virapratap
22
Asst. Professor
CSE Dept, V.R.S.E.C
Advantage of Garbage Collection:

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

4.8. Overloading Methods

If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading. If we have to perform only one operation, having same name of the methods
increases the readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three
parameters then it may be difficult for you as well as other programmers to understand the behavior of
the method because its name differs. So, we perform method overloading to figure out the program
quickly.

There are two ways to overload the method in java

• By changing the no. of arguments


• By changing the datatype

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two numbers and
second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for calling
methods.

class Adder
{
int add(int a,int b){return a+b;}
int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading
{
public static void main(String[] args)
{
Adder ob=new Adder();
System.out.println(ob.add(11,11));
System.out.println(ob.add(11,11,11));
}
Mr.Raghu Virapratap
23
Asst. Professor
CSE Dept, V.R.S.E.C
}
w
Output:
22
33

2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method receives
two integer arguments and second add method receives two double arguments.

class Adder
{
int add(int a, int b){return a+b;}
double add(double a, double b){return a+b;}
}
class TestOverloading
{
public static void main(String[] args)
{
Adder ob=new Adder();
System.out.println(ob.add(11,11));
System.out.println(ob.add(12.3,12.6));
}
}
Test it Now
Output:
22
24.9

4.9. Passing and Returning Objects in Java:

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.

Mr.Raghu Virapratap
24
Asst. Professor
CSE Dept, V.R.S.E.C
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.In Java
we can pass objects to methods.

For example, consider the following program :

// Java program to demonstrate objects

// passing to methods.

public 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

Mr.Raghu Virapratap
25
Asst. Professor
CSE Dept, V.R.S.E.C
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);

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.

Mr.Raghu Virapratap
26
Asst. Professor
CSE Dept, V.R.S.E.C
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));

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

Mr.Raghu Virapratap
27
Asst. Professor
CSE Dept, V.R.S.E.C
we can use 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);

Mr.Raghu Virapratap
28
Asst. Professor
CSE Dept, V.R.S.E.C
// get volume of myclone
vol = myclone.volume();
System.out.println("Volume of myclone is " + vol);
}
}
Output:
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
Mr.Raghu Virapratap
29
Asst. Professor
CSE Dept, V.R.S.E.C
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.

4.10. Nested Classes in Java

In java, it is possible to define a class within another class, such classes are known
as nested classes. They enable you to logically group classes that are only used in one place, thus this
increases the use of encapsulation, and create more readable and maintainable code.

The scope of a nested class is bounded by the scope of its enclosing class. Thus in above example,
class NestedClass does not exist independently of class OuterClass.

A nested class has access to the members, including private members, of the class in which it is nested.
However, reverse is not true i.e. the enclosing class does not have access to the members of the nested
class.A nested class is also a member of its enclosing class.

As a member of its enclosing class, a nested class can be declared private, public, protected,
or package private(default).

Nested classes are divided into two categories:

static nested class : Nested classes that are declared static are called static nested classes.

inner class : An inner class is a non-static nested class.

Syntax:

class OuterClass
{
...
class NestedClass
{
...
}
}

Mr.Raghu Virapratap
30
Asst. Professor
CSE Dept, V.R.S.E.C
Static nested classes

As with class methods and variables, a static nested class is associated with its outer class. And like static
class methods, a static nested class cannot refer directly to instance variables or methods defined in its
enclosing class: it can use them only through an object reference.
They are accessed using the enclosing class name.

OuterClass.StaticNestedClass

For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

// Java program to demonstrate accessing


// a static nested class
// outer class
class OuterClass
{
// static member
static int outer_x = 10;

// instance(non-static) member
int outer_y = 20;

Mr.Raghu Virapratap
31
Asst. Professor
CSE Dept, V.R.S.E.C
// private member
private static int outer_private = 30;

// static nested class


static class StaticNestedClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);

// can access display private static member of outer class


System.out.println("outer_private = " + outer_private);

// The following statement will give compilation error


// as static nested class cannot directly access non-static membera
// System.out.println("outer_y = " + outer_y);

}
}
}

// Driver class
public class StaticNestedClassDemo
{
public static void main(String[] args)
{
// accessing a static nested class
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

nestedObject.display();

}
}
Output:
outer_x = 10
outer_private = 30

Mr.Raghu Virapratap
32
Asst. Professor
CSE Dept, V.R.S.E.C
Inner classes
To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within
the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

There are two special kinds of inner classes :

• Local inner classes


• Anonymous inner classes

// Java program to demonstrate accessing


// a inner class

// outer class
class OuterClass
{
// static member
static int outer_x = 10;

// instance(non-static) member
int outer_y = 20;

// private member
private int outer_private = 30;

// inner class
class InnerClass
{
void display()
{
// can access static member of outer class
System.out.println("outer_x = " + outer_x);

// can also access non-static member of outer class


System.out.println("outer_y = " + outer_y);

// can also access private member of outer class


System.out.println("outer_private = " + outer_private);

}
}
}

Mr.Raghu Virapratap
33
Asst. Professor
CSE Dept, V.R.S.E.C
// Driver class
public class InnerClassDemo
{
public static void main(String[] args)
{
// accessing an inner class
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();

innerObject.display();

}
}
Output:

outer_x = 10

outer_y = 20

outer_private = 30

Difference between static and inner(non-static nested) classes

Static nested classes do not directly have access to other members(non-static variables and
methods) of the enclosing class because as it is static, it must access the non-static members of its
enclosing class through an object. That is, it cannot refer to non-static members of its enclosing class
directly. Because of this restriction, static nested classes are seldom used.

Non-static nested classes (inner classes) has access to all members(static and non-static variables
and methods, including private) of its outer class and may refer to them directly in the same way that
other non-static members of the outer class do.

Mr.Raghu Virapratap
34
Asst. Professor
CSE Dept, V.R.S.E.C

You might also like