Oop Java Unit 2
Oop Java Unit 2
Belagavi
Sai Vidya Institute of Technology
Bangalore
1. Introduction to Classes
Classes & Objects, Assigning Object Reference
Variables
Constructor, This Keyword, Garbage Collection
Class Fundamentals
Declaring Objects
Example
Assignment
Class fundamentals
So, we can say that class is a template for an object and an object is an
instance of a class.
Most of the times, the terms object and instance are used interchangeably.
Class fundamentals
Class fundamentals
Class fundamentals- declaring class
A class contains data (member or instance variables) and the code (member
methods) that operate on the data.
The general form can be given as –
• class class name
• {
• type var1; Here, class name is any valid name given to the class.
• type var2; Variables declared within a class are called as
• ……. instance variables because every instance (or object) of
• type method1(para_list)
a class contains its own copy of these variables.
• {
•
The code is contained within methods.
//body of method1
• } Methods and instance variables collectively called as
• type method2(para_list) members of the class
• { The instance variables are acted upon and accessed
• //body of method2
only the methods defined for that class
• }
• ………..
• }
Class fundamentals- declaring object
The statement Box mybox= new Box(); can be viewed as 2 statements as follows
• Box mybox; // delcare a reference to object of the class Box and initialized to null
• mybox= new Box();// allocate memory for Box object and assigns the reference to
mybox
declaring objects using new operator
null
Assigning object reference variables
Object reference variables act differently when an assignment takes place.
For Example:
class Box
{
int width;
int height;
int depth;
}
public class Main OUTPUT:
{ myBox1.width:20
public static void main(String args[]) myBox2.width:20
{
Box myBox1 = new Box();
Box myBox2 = myBox1;
myBox1.width = 10;
myBox2.width = 20;
System.out.println("myBox1.width:" + myBox1.width);
System.out.println("myBox2.width:" + myBox2.width);
}
}
Introducing methods
Classes usually consist of two things: instance variables and methods.
Instance variables are the data part of a class, while the methods defines the behaviors of
a class.
Most of the time, methods are used to access the instance variables defined by the class
Syntax: This is the general form of a method:
type name(parameter-list)
{
// body of method
}
type specifies the type of data returned by the method. If the method does not return a
value, its return type must be void.
The name of the method is specified by name.
The parameter-list is a sequence of type and identifier pairs separated by commas.
Parameters receives the value of the arguments passed to the method. If the method has
no parameters, then the parameter list will be empty.
Adding method
• Method With parameters
• Method Without Parameters
• Method Return a value
• The type of data returned by a method must be
compatible with the return type specified by the
method.
• The variable receiving the value returned by a
method must also be compatible with the return
type specified for the method.
Constructors
• Automatic initialization of an object is performed through
the use of a constructor.
• A constructor initializes an object immediately upon creation.
• It has the same name as the class in which it resides and is
syntactically similar to a method.
• Once defined, the constructor is automatically called
immediately after the object is created, before the new operator
completes.
• Constructors have no return type, not even void. This is because
the implicit return type of a class constructor is the class type
itself.
• The constructor’s job to initialize the internal state of an object.
Construc
tors
• Constructors are
1. Automatic Constructors
2. Default Constructors
Box mybox1 = new Box();
The default constructor automatically initializes
all instance variables to zero.
3. Parameterized Constructors
Box mybox1 = new Box(10, 20, 15);
4. Copy Constructors
class Box { 1. Default
double width; Constructors
double height;
double depth;
// This is the
constructor for
Box.
Box() {
System.ou
t.println("
depth = 10;
} Constructi class BoxDemo6 {
ng Box");
// compute and return volume public static void main(String args[]) {
width
double =
volume() { // declare, allocate, and initialize Box
10;
return width * height * depth; objects Box mybox1 = new Box();
} height = Box mybox2 = new Box();
} 10; double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " +
OUTPUT: vol);
Volume is 3000.0 // get volume of second box
Volume is 162.0 vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
class Box { Parameterized Constructors
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; class BoxDemo7 {
} public static void main(String args[]) {
// compute and return volume // declare, allocate, and initialize Box objects
double volume() { Box mybox1 = new Box(10, 20, 15);
return width * height * depth; Box mybox2 = new Box(3, 6, 9);
} double vol;
} // get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
OUTPUT: // get volume of second box
Constructing Box vol = mybox2.volume();
Constructing Box System.out.println("Volume is " + vol);
Volume is 1000.0 }
Volume is 1000.0 }
The this
Keyword
• Sometimes a method will need to refer to the
object that invoked it.
• To allow this, Java defines the this keyword.
• this can be used inside any method to refer to the
current object. That is, this is always a reference to
the object on which the method was invoked.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
• Usage of java this keyword
1. this can be used to refer current class instance
variable.
2. this can be used to invoke current class method
(implicitly)
3. this() can be used to invoke current class
constructor.
4. this can be passed as an argument in the
method call.
5. this can be passed as argument in the constructor
call.
6. this can be used to return the current class instance
from the method.
class Abc {
int val;
Abc() {
System.out.println("Default Constructor Called");
}
Abc(int x)
{
this();
val=x;
Syste
m.ou
t.prin
tln("P
aram
Const
ructo
r"+
this.v
al);
}
}
class ThisEx {
Garbage Collection
• Since objects are dynamically allocated by using the new
operator, how such objects are destroyed and their
memory released for later reallocation?
• In some languages, such as C++, dynamically
allocated objects must be manually released by use of
a delete operator.
• Java takes a different approach; it handles deallocation
automatically. The technique that accomplishes this is
called garbage collection.
• When no references to an object exist, that object is
assumed to be no longer needed, and the memory
occupied by the object can be reclaimed.
Garbage Collection
• There is no explicit need to destroy objects.
• Garbage collection only occurs sporadically (if at all)
during the execution of your program.
• It will not occur simply because one or more objects exist
that are no longer used. Furthermore, different Java run-
time implementations will take varying approaches to
garbage collection.
• Do not to think about it while writing your programs.
Methods & Classes
class Box
{
int width;
int height;
int depth;
void calculateVolume()
{
System.out.print("Volume is ");
Note: When an instance variable is accessed by
System.out.println(width * height * depth);
} code that is not part of the class in which instance
} variable is defined , then it must be accessed
public class BoxDemo through an object and dot operator.
{ However, When an instance variable is accessed
public static void main(String args[]) by code that is part of the class in which instance
{ variable is defined , then it can be referred
Box mybox1 = new Box();
directly.
mybox1.width = 10;
mybox1.height = 20;
This is applied to methods also.
mybox1.depth = 15;
mybox1.calculateVolume();
}
}
oVERLOADING methods - example
• In Java it is possible to define two or more methods within the same class that
share the same name, as long as their parameter declarations are different.
• When this is the case, the methods are said to be overloaded, and the
process is referred to as method overloading.
• Method overloading is one of the ways that Java supports polymorphism.
• When an overloaded method is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded method to
actually call.
• Thus, overloaded methods must differ in the type and/or number of their
parameters.
• While overloaded methods may have different return types, the return type alone
is insufficient to distinguish two versions of a method.
:Method Overloading
• Method Overloading is a feature that allows a class to have more than one
method having the same name, if their argument lists are different.
• It is similar to constructor overloading in Java, that allows a class to have
more than one constructor having different argument lists.
• Three ways to overload a method
1.Number of parameters.
add(int, int)
add(int, int, int)
2.Data type of parameters.
add(int, int) add(int,
float)
3.Sequence of Data type of parameters.
add(int, float)
add(float, int)
• Invalid case of method overloading:
int add(int, int) float
add(int, int)
:Method Overloading
• Method Overloading is a feature that allows a class to have more than one
method having the same name, if their argument lists are different.
• It is similar to constructor overloading in Java, that allows a class to have
more than one constructor having different argument lists.
• Three ways to overload a method
1.Number of parameters.
add(int, int)
add(int, int, int)
2.Data type of parameters.
add(int, int) add(int,
float)
3.Sequence of Data type of parameters.
add(int, float)
add(float, int)
• Invalid case of method overloading:
int add(int, int) float
add(int, int)
// Demonstrate method overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters"); // Demonstrate method overloading.
} class OverloadDemo {
// Overload test for one integer void test() {
System.out.println("No parameters");
parameter. void test(int a) { }
System.out.println("a: " + a); // Overload test for one integer
} parameter. void test(int a) {
// Overload test for two integer System.out.println("a: " + a);
}
parameters. void test(int a, int b) { // Overload test for two integer
System.out.println("a and b: " + a + " parameters. void test(int a, int b) {
" + b); System.out.println("a and b: " + a + " " + b);
} }
// overload test for a double // overload test for a double
parameter double test(double a)
parameter double test(double a) { { System.out.println("double a: " + a);
System.out.println("double a: " + return a*a;
a); return a*a; }
} }
}
// Automatic type conversions apply to
overloading. class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double
parameter void test(double a) {
System.out.println("Inside test(double)
a: " + a);
}
}
class Overload {
public static void main(String args[])
{ OverloadDemo ob = new
OverloadDemo(); int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i); // this will invoke test(double)
ob.test(123.2); // this will invoke
test(double)
// Constructor Overloading class OverloadCons {
class Box Overloading Constructors public static void main(String args[]) {
{ double width; // create boxes using the various
double height; constructors Box mybox1 = new Box(10, 20,
double depth; 15);
Box(double w, double h, double d) { Box mybox2 = new Box();
width = w; Box mycube = new
Box(7); double vol;
height = h;
// get volume of first box
depth = d; vol = mybox1.volume();
} System.out.println("Volume of mybox1 is " +
Box() { vol);
width = -1; // use -1 to indicate // get volume of second
height = -1; // an uninitialized box vol = mybox2.volume();
depth = -1; // box System.out.println("Volum
} e of mybox2 is " + vol);
Box(double len) { // get volume of cube
vol =
width = height = depth = len;
mycube.volume();
} System.out.println("Vo
double volume() { OUTPUT lume of mycube is " +
return width * height * depth; Volume of mybox1 is 3000.0 vol);
} Volume of mybox2 is -1.0 }
} Volume of mycube is 343.0 }
:Using Objects as Parameters
// Objects may be passed to
methods. class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
} class PassOb {
// return true if o is equal to public static void main(String
the invoking object args[]) { Test ob1 = new Test(100,
22);
boolean equals(Test o) { Test ob2 = new Test(100, 22);
if(o.a == a && o.b == b) return Test ob3 = new Test(-1, -1);
true; System.out.println("ob1 == ob2: " +
else return false; ob1.equals(ob2)); System.out.println("ob1 ==
OUTPUT ob3: " + ob1.equals(ob3));
}
ob1 == ob2: }
} true ob1 == }
ob3: false
class Box
{ double
width; double
height;
double depth;
// Notice this
constructor. It
takes an
object of type
Box.
Box(Box ob) { // pass object to
constructor width = ob.width;
height = ob.height;
depth = ob.depth;
}
// constructor used when all dimensions
specified Box(double w, double h, double d) {
width = w; // compute and return
height = h; volume double volume() {
depth = d;
return width * height *
}
// constructor used when no dimensions depth;
specified Box() { }
width = -1; // use -1 to }
indicate height = -1; // an
uninitialized depth = -1; // box
}
class OverloadCons2 {
public static void main(String args[]) {
// create boxes using the various
constructors Box mybox1 = new Box(10,
20, 15);
Box mybox2 = new
Box(); Box mycube =
new Box(7);
Box myclone = new Box(mybox1); // create copy of
mybox1 double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " +
vol);
// get volume of second
box vol =
mybox2.volume();
System.out.println("Volu
me of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of cube is " +
vol);
Argument Passing
• there are two ways that a computer language can pass
an argument to a subroutine.
– call-by-value
– call-by-reference
• Java uses both approaches, depending upon what is
passed.
• In Java, when you pass a primitive type to a method, it is
passed by value.
• When you pass an object to a method, it is call-by-
reference.
• When a primitive type is passed to a method, it is done
by use of call-by-value. Objects are implicitly passed by
use of call-by-reference.
// Objects are passed by
reference. class Test { OUTPUT
int a, b; ob.a and ob.b before call: 15
Test(int i, int j) { 20 ob.a and ob.b after call: 30
a = i; 10
b = j;
}
// pass an object
void meth(Test o)
{
a. *= 2;
b. /= 2;
}
}
class CallByRef {
public static void main(String args[])
{System.out.println("ob.a
Test ob = new Test(15, 20);
and ob.b before call: " + ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}
}
Returning Objects