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

Oop Java Unit 2

Uploaded by

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

Oop Java Unit 2

Uploaded by

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

Visvesvaraya Technological University

Belagavi
Sai Vidya Institute of Technology
Bangalore

Department of CSE (Artificial Intelligence & Machine


Learning)
JAVA
COMPLETE REFERENCE

MODULE 2 : Classes and Methods

Mr. BASWANTHRAO PATIL


Assistant Professor,
Dept. of CSE (AI & ML),
1
SVIT, Bangalore.
• AGENDA :

1. Introduction to Classes
Classes & Objects, Assigning Object Reference
Variables
Constructor, This Keyword, Garbage Collection

2. Methods and Classes


Overloading Methods, Objects as Parameters, Argument
Passing, Returning .Objects, Recursion, Access Control,
Understanding static, Introducing final, Introducing Nested and
Inner Classes.
AGENDA

Class Fundamentals
Declaring Objects
Example
Assignment
Class fundamentals

A Class is a user-defined data type in Java that defines a template or blueprint


for an object.
We can create any number of variables (objects) of that data type.

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

Creating a class means having a user-defined data type.


To have a variable of this new data type, we should create an
object
Objects are created dynamically using the new operator

Syntax: <classname> <objectname>=new <classname>();


declaring objects

Creating a class means having a user-defined data type.


To have a variable of this new data type, we should create an object
Objects are created dynamically using the new operator
Syntax: <classname> <objectname>=new <classname>();
declaring objects using new operator

The new operator dynamically allocates the memory for an 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:

• Box b1=new Box(); Is b2 assigned a copy of the object referred


by b1, i.e., b1 and b2 refer to separate and
distinct objects
• Box b2=b1;
After this fragment executes, b1 and b2 will both refer to the same object.
The assignment of b1 to b2 did not allocate any memory or copy any part of the
original object.
It simply makes b2 refer to the same object as does b1.
Thus, any changes made to the object through b2 will affect the object to which
b1 is referring.
Assigning object reference variables

Note: When we are assigning one object


variable to another object variable, we
are not creating copy of the object but
making copy of the reference
Assigning object reference variables-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

• A method can return any type of data, including class types.


// Returning an object.
class Test OUTPUT
{ int a; ob1.a: 2
Test(int i) { ob2.a: 12
a = i; ob2.a after second increase: 22
}
Test
incrByTen()
{
Test
temp =
new
Test(a+
10);
return
temp;
}
}
class RetOb
{ System.out.println("ob2.a after second increase: "+ ob2.a);
public
} static void main(String
} args[]) { Test ob1 = new
Recursion :
• Java supports recursion.
• Recursion is the process of defining something in
terms of itself.
• Recursion is the attribute that allows a method to
call itself.
• A method that calls itself is said to be recursive.
class Test
{ int a; // default access
public int b; // public access
private int c; // private access
void setc(int i) { // set c's value
c = i;
}
int getc() // get c's value
{ return c;
}
}
class public static void main(String args[])
AccessTest { { Test ob = new Test();
ob.a = 10; // These are OK, a and b may be accessed directly ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error!
// You must access c through its methods ob.setc(100);
// OK
System.out.println("a, b, and c: " + ob.a + " " +ob.b + " " +
ob.getc());
}
}
fin
al
• The final keyword in java is used to restrict the
user.
• The java final keyword can be used in many
context.
1. variable
2. method
3. class

final variable
A variable can be declared as final.
• Doing so prevents its contents from being modified.
• This means that you must initialize a final variable when it is declared.
• It is a common coding convention to choose all uppercase identifiers for final
variables.
• Variables declared as final do not occupy memory on a per-instance basis.
• Thus, a final variable is essentially a constant.
• A field that is both static and final has only one piece of storage that cannot be
changed.
• The keyword final can also be applied to methods, and classes.
• A final variable that is not initialized at the time of declaration is known as
blank
final variable. We can initialize using constructors only.
• A static final variable that is not initialized at the time of declaration is known as
static blank final variable. It can be initialized
class A{ only in static block.
final int FILE_NEW = 1;
static final int data;//static blank final variable
final int FILE_OPEN = 2;
static{ data=50;}
final int FILE_SAVE = 3; public static void main(String args[]){
final int FILE_SAVEAS = 4; System.out.println(A.data);
final int FILE_QUIT = 5; }
}
final variable
class Bike11{
• If you declare any int cube(final int n){
parameter as final, you n=n+2; //can't be changed as n is final
cannot change the }
n*n*n;
value of it. public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}

Can we declare a constructor final?


No, because constructor is never inherited.
class finalvar{
final int x=90; //final variable
void run(){
x=400;
}
public static void main(String args[])
{
finalvar obj=new
finalvar(); obj.run();
}
}//end of class

Output: Compile Time Error


final method
• If you make any method as final, you cannot override it.
• Is final method inherited?
Yes, final method is inherited but you cannot override it.
class Bike{
final void run(){
System.out.println("running");
}
}
class Honda extends Bike{
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error

You might also like