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

Java Module-2

JAVA MODULE 2

Uploaded by

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

Java Module-2

JAVA MODULE 2

Uploaded by

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

1

JSS Academy of Technical Education Bengaluru


Department of Computer Science and Engineering
Object Oriented Programming with JAVA
Module-2
By,
Dr Vikhyath K B

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Module-2 Introducing classes
2

The class is at the core of the Java. The class is the logical construct upon which the
entire Java language is built because it defines the shape and nature of an object.

The class forms the basis for object-oriented programming in Java. Any concept you
wish to implement in a Java program must be encapsulated within a class.

Class Fundamentals

Till now classes are used to encapsulate the main( ) method, which has been used to
demonstrate the basics of the Java syntax.

The General Form of a Class

classes contain code and data. A class’ code defines the interface to its data.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


3

¨ A class is declared by use of the class keyword. A simplified general form


of a class definition is shown here:

class classname
{
type instance-variable1;
type instance-variable2;

type instance-variableN;
type methodname1(parameter-list)
{
}
type methodname2(parameter-list)
{
}
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
4

….

type methodname3(parameter-list)
{
}
}
¨ 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, as a general rule, it is the methods
that determine how a class’ data can be used.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


5

¨ Variables defined within a class are called instance variables because each
instance of the class (that is, each object of the class) contains its own copy
of these variables. Thus, the data for one object is separate and unique from
the data for another.

A Simple Class

¨ Here is a class called Box that defines three instance variables: width,
height, and depth. Currently, Box does not contain any methods.
class Box
{
double width;
double height;
double depth;
} Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
6

¨ It is important to remember that a class declaration only creates a template;


it does not create an actual object.

¨ To actually create a Box object, use a statement like the following:

Box mybox = new Box(); // create a Box object called mybox

¨ After this statement executes, mybox will be an instance of Box. Thus, it


will have “physical” reality.

¨ Every Box object will contain its own copies of the instance variables
width, height, and depth. To access these variables, use the dot (.) operator.
The dot operator links the name of the object with the name of an instance
variable.
mybox.width = 100;
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
7

¨ This statement tells the compiler to assign the copy of width that is
contained within the mybox object the value of 100. In general, use the dot
operator to access both the instance variables and the methods within an
object.
* A program that uses the Box class.
Call this file BoxDemo.java */
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


8

class BoxDemo
{
public static void main(String args[])
{
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10; Output:
mybox.height = 20; Volume is 3000.0
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
}
9

/ 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;
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
10

// 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; Output:
mybox2.height = 6; Volume is 3000.0
mybox2.depth = 9; Volume is 162.0
// 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);
} Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24

}
Declaring Objects
11

¨ when we create a class, we are creating a new data type. we can use this
type to declare objects of that type.

Obtaining objects of a class is a two-step process.

¨ First, declare a variable of the class type. This variable does not define an
object. Instead, it is simply a variable that can refer to an object.

¨ Second, acquire an actual, physical copy of the object and assign it to that
variable. We can do this using the new operator.

¨ The new operator dynamically allocates (that is, allocates at run time)
memory for an object and returns a reference to it.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


12

Box mybox = new Box();

¨ This statement combines the two steps just described. It can be rewritten
like this to show each step more clearly:

Box mybox; // declare reference to object


mybox = new Box(); // allocate a Box object

¨ The first line declares mybox as a reference to an object of type Box. After
this line executes, mybox contains the value null, which indicates that it
does not yet point to an actual object.

¨ Any attempt to use mybox at this point will result in a compile-time error.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


13

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Assigning Object Reference Variables
14

¨ Object reference variables act differently than we might expect when an


assignment takes place.
¨ Box b1 = new Box();
¨ Box b2 = b1;

¨ Here, b1 and b2 are not referring to the separate objects. They refer to the
same object.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


15

¨ Although b1 and b2 both refer to the same object, they are not linked in
any other way. For example, a subsequent assignment to b1 will simply
unhook b1 from the original object without affecting the object or affecting
b2. For example:

Box b1 = new Box();


Box b2 = b1; //
...
b1 = null;

¨ Here, b1 has been set to null, but b2 still points to the original object.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Introducing Methods
16

Classes usually consist of two things: instance variables and methods. The
Java gives methods so much power and flexibility.

This is the general form of a method:

type name(parameter-list)
{
// body of method
}
¨ Here, type specifies the type of data returned by the method. This can be
any valid type, including class types that you create.

¨ If the method does not return a value, its return type must be void. The
name of the method is specified by name.
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
17

¨ Methods that have a return type other than void return a value to the
calling routine using the following form of the return statement:

return value;

¨ Here, value is the value returned.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Adding a Method to the Box Class
18

// This program includes a method inside the box class.


class Box
{
double width;
double height;
double depth;
// display volume of a box
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
19

class BoxDemo3
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to mybox1's instance variables

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

/* assign different values to mybox2's instance


variables */
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
20

mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume();
// display volume of second box
mybox2.volume();
}
}
Output:
Volume is 3000.0
Volume is 162.0

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Returning a Value
21

¨ The following example, an improved version of the preceding program.


// Now, volume() returns the volume of a box.
class Box
{
double width;
double height;
double depth;
// compute and return volume
double volume()
{
return width * height * depth;
}
}
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
22

class BoxDemo4
{
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 */
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
23

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

// get volume of first box


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

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
24

vol = mybox1.volume();

¨ The value of mybox1.volume( ) is 3,000 and this value then is stored in vol.

¨ There are two important things to understand about returning values:

¨ The type of data returned by a method must be compatible with the return
type specified by the method. For example, if the return type of some
method is boolean, you could not return an integer.

¨ The variable receiving the value returned by a method(such as vol, in this


case)must also be compatible with the return type specified for the method.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


25

¨ One more point: The preceding program can be written a bit more efficiently
because there is actually no need for the vol variable.

¨ The call to volume( ) could have been used in the println( ) statement directly,
as shown here:

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

¨ In this case, when println( ) is executed, mybox1.volume( ) will be called


automatically and its value will be passed to println( ).

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Adding a Method That Takes Parameters
26

¨ While some methods don’t need parameters, most do. Parameters allow a
method to be generalized. That is, a parameterized method can operate on
a variety of data and/or be used in a number of slightly different
situations. To illustrate this point, let’s use a very simple example. Here is a
method that returns the square of the number 10:

int square()
{
return 10 * 10;
}

¨ While this method does, indeed, return the value of 10 squared, its use is
very limited. However, if you modify the method so that it takes a
parameter, as shown next, then you can make square( ) much more useful.
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
27

int square(int i)
{
return i * i;
}
¨ Now, square( ) will return the square of whatever value it is called with.
That is, square( ) is now a general-purpose method that can compute the
square of any integer value, rather than just 10.
Here is an example:
int x, y;
x = square(5); // x equals 25
x = square(9); // x equals 81
y = 2;
x = square(y); // x equals 4
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
28

// This program uses a parameterized method.


class Box
{
double width;
double height;
double depth;
// compute and return volume
double volume()
{
return width * height * depth;
}
// sets dimensions of box

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


29

void setDim(double w, double h, double d)


{
width = w;
height = h;
depth = d;
}
}
class BoxDemo5
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
30

double vol;
// initialize each box
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Constructors
31

¨ Java allows objects to initialize themselves when they are created. This
automatic initialization 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 look a little strange because they have no return type, not
even void.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


32

class Box
{
double width;
double height;
double depth; // This is the constructor for Box.
Box()
{
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
double volume()
{
return width * height * depth;
}
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
}
33

class BoxDemo6
{
public static void main(String args[])
{ // declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
}
Parameterized Constructors
34

For example, the following version of Box defines a parameterized constructor


that sets the dimensions of a box as specified by those parameters. Pay special
attention to how Box objects are created.
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;
}
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
35

// compute and return volume


double volume()
{
return width * height * depth;
}
}
class BoxDemo7
{
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;
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
36

// get volume of first box


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

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Output:
¨ Volume is 3000.0
¨ Volume is 162.0

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


The this Keyword
37

¨ 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. You can use this anywhere a reference to an object of the current
class’ type is permitted.

// A redundant use of this.


Box(double w, double h, double d)
{
this.width = w;
this.height = h;
this.depth = d;
}
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
Instance Variable Hiding
38

¨ As we know, it is illegal in Java to declare two local variables with the same
name inside the same or enclosing scopes.

¨ Interestingly, you can have local variables, including formal parameters to


methods, which overlap with the names of the class’ instance variables.

¨ However, when a local variable has the same name as an instance variable,
the local variable hides the instance variable.
// Use this to resolve name-space collisions.
Box(double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
}
Garbage Collection
39

¨ 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 for you


automatically. The technique that accomplishes this is called garbage
collection.

¨ It works like this: 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.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


The finalize( ) Method
40

¨ Sometimes an object will need to perform some action when it is destroyed.

For example, if an object is holding some non-Java resource such as a file


handle or character font, then you might want to make sure these resources
are freed before an object is destroyed.

¨ To handle such situations, Java provides a mechanism called finalization.


By using finalization, you can define specific actions that will occur when
an object is just about to be reclaimed by the garbage collector.

The finalize( ) method has this general form:


protected void finalize( )
{
// finalization code here
} Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
A Stack Class
41

¨ A stack stores data using first-in, last-out ordering. That is, a stack is like a
stack of plates on a table—the first plate put down on the table is the last
plate to be used.

¨ Stacks are controlled through two operations traditionally called push and
pop. To put an item on top of the stack, you will use push. To take an item
off the stack, you will use pop.
class Stack
{
int stck[] = new int[10];
int tos;
// Initialize top-of-stack
Stack()
{
tos = -1;
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
}
42

// Push an item onto the stack


void push(int item)
{
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
// Pop an item from the stack
int pop()
{
if(tos < 0)
{ System.out.println("Stack underflow.");
return 0;
} JSS ATE Bengaluru 560060
Vikhyath K B, Dept of CSE, 18/09/24
43

else
return stck[tos--];
}
}
class TestStack
{
public static void main(String args[])
{
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
// push some numbers onto the stack
for(int i=0; i<10; i++) mystack1.push(i);
for(int i=10; i<20; i++) mystack2.push(i);
// pop those numbers off the stack
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru
18/09/24
560060
44

System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");

for(int i=0; i<10; i++)


System.out.println(mystack2.pop());
}
}

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Overloading Methods
45

¨ 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.
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
46

// Demonstrate method overloading.


class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
// Overload test for one integer parameter. void
test(int a)
{
System.out.println("a: " + a);
}

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


47

// 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
double test(double a)
{
System.out.println("double a: " + a);
return a*a;
}
}

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


48

class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " +
result);
} Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
}
49

Output:
¨ No parameters
¨ a: 10
¨ a and b: 10 20
¨ double a: 123.25
¨ Result of ob.test(123.25): 15190.5625

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


50

// 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);
}

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


51

// 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();

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


52

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)
}
}
Output:
¨ No parameters
¨ a and b: 10 20
¨ Inside test(double) a: 88
¨ Inside test(double) a: 123.2
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
Overloading Constructors
53

¨ 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.
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;
Vikhyath K B,depth = d;
Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
}
54

// compute and return volume


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

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


55

/* Here, Box defines three constructors to initialize the


dimensions of a box various ways. */
class Box
{
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
56

// constructor used when no dimensions specified


Box()
{
width = -1;
height = -1;
depth = -1;
}
// constructor used when cube is created
Box(double len)
{
width = height = depth = len;
}

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


57

// compute and return volume


double volume()
{
return width * height * depth;
}
}
class OverloadCons
{
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);
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
58

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("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Using Objects as Parameters
59

¨ So far, we have only been using simple types as parameters to methods.


However, it is both correct and common to pass objects to methods.

// Objects may be passed to methods.


class Test
{ int a, b;
Test(int i, int j)
{
a = i; b = j;
}
// return true if o is equal to the invoking object
boolean equals(Test o)
{
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
60

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


return true;
else
return false;
}
}

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


{
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
61

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


}
}

Output:
ob1 == ob2: true
ob1 == ob3: false

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


62

// Here, Box allows one object to initialize another.


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;
Vikhyath K B,depth = ob.depth;
Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
}
63

// constructor used when all dimensions specified


Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box()
{
width = -1;
height = -1;
depth = -1;
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
}
64

// constructor used when cube is created


Box(double len)
{
width = height = depth = len;
}
// compute and return volume
double volume()
{ return width * height * depth;
}
}

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


65

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);
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
66

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube vol = mycube.volume();
System.out.println("Volume of cube is " + vol);
// get volume of clone
vol = myclone.volume();
System.out.println("Volume of clone is " + vol);
}
}

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


A Closer Look at Argument Passing
67

¨ In general, there are two ways that a computer language can pass an
argument to a subroutine.

¨ The first way is call-by-value. This approach copies the value of an


argument into the formal parameter of the subroutine. Therefore, changes
made to the parameter of the subroutine have no effect on the argument.

¨ The second way an argument can be passed is call-by-reference. In this


approach, a reference to an argument (not the value of the argument) is
passed to the parameter.

¨ Inside the subroutine, this reference is used to access the actual argument
specified in the call. This means that changes made to the parameter will
affect the argument used to call the subroutine.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


68

¨ As you will see, 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.


Thus, what occurs to the parameter that receives the argument has no effect
outside the method. For example, consider the following program:

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


69

// Primitive types are passed by value.


class Test
{
void meth(int i, int j)
{
i *= 2;
j /= 2;
}
}
class CallByValue
{
public static void main(String args[])
{
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
70

Test ob = new Test();


int a = 15, b = 20;
System.out.println("a and b before call: " + a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " + a + " " + b);
}
}
Output:
a and b before call: 15 20
a and b after call: 15 20

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


71

// Objects are passed by reference.


class Test
{
int a, b;
Test(int i, int j)
{
a = i; b = j;
}
// pass an object
void meth(Test o)
{
o.a *= 2;
o.b /= 2;
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
}
}
72

class CallByRef
{
public static void main(String args[])
{
Test ob = new Test(15, 20);
System.out.println("ob.a 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);
}
}
Output:
ob.a and ob.b before call: 15 20
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
ob.a and ob.b after call: 30 10
Returning Objects
73

A method can return any type of data, including class types that you create.
For example, in the following program, the incrByTen( ) method returns an
object in which the value of a is ten greater than it is in the invoking object.
// Returning an object.
class Test
{
int a;
Test(int i)
{
a = i;
}
Test incrByTen()
{
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
74

Test temp = new Test(a+10);


return temp;
}
}
class RetOb
{
public static void main(String args[])
{
Test ob1 = new Test(2);
Test ob2;
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
75

ob2 = ob2.incrByTen();
System.out.println("ob2.a after second increase: " +
ob2.a);
}
}

Output:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Recursion
76

¨ Java supports recursion. Recursion is the process of defining something in


terms of itself. As it relates to Java programming, recursion is the attribute
that allows a method to call itself. A method that calls itself is said to be
recursive.
// A simple example of recursion.
class Factorial
{
// this is a recursive method
int fact(int n)
{
int result;
if(n==1)
return 1;
result = fact(n-1) * n; return result;
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
77

}
}
class Recursion
{
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


78

Output:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Introducing Access Control
79

¨ As you know, encapsulation links data with the code that manipulates it.
However, encapsulation provides another important attribute: access
control.

¨ Through encapsulation, you can control what parts of a program can access
the members of a class. By controlling access, you can prevent misuse.

¨ Java’s access specifiers are public, private, and protected. Java also defines
a default access level. protected applies only when inheritance is involved.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


80

¨ When a member of a class is modified by the public specifier, then that


member can be accessed by any other code. When a member of a class is
specified as private, then that member can only be accessed by other
members of its class.

¨ Now you can understand why main( ) has always been preceded by the
public specifier. It is called by code that is outside the program—that is, by
the Java run-time system.

¨ When no access specifier is used, then by default the member of a class is


public within its own package, but cannot be accessed outside of its
package.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


81

¨ In the classes developed so far, all members of a class have used the default
access mode, which is essentially public. However, this is not what you will
typically want to be the case.

¨ Usually, you will want to restrict access to the data members of a class—
allowing access only through methods. Also, there will be times when you
will want to define methods that are private to a class.

¨ An access specifier precedes the rest of a member’s type specification. That


is, it must begin a member’s declaration statement. Here is an example:

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


82

public int i;
private double j;
private int myMethod(int a, char b)
{ // ...

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


83

/* This program demonstrates the difference between public


and private. */
class Test
{
int a;
public int b;
private int c;
// methods to access c
void setc(int i)
{
// set c's value
c = i;
}
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
84

int getc()
{
// get c's value
return c;
}
}
class AccessTest
{
public static void main(String args[])
{
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10; ob.b = 20;

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


85

// 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());
}
}

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


86

// This class defines an integer stack that can hold 10


values.
class Stack

{ /* Now, both stck and tos are private. This means that
they cannot be accidentally or maliciously altered in a
way that would be harmful to the stack. */

private int stck[] = new int[10];


private int tos;
// Initialize top-of-stack
Stack()
{
tos = -1;
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
}
87

// Push an item onto the stack


void push(int item)
{
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
// Pop an item from the stack
int pop()
{
if(tos < 0)
{
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
88

System.out.println("Stack underflow.");
return 0;
}
else
return stck[tos--];
}
}
class TestStack
{
public static void main(String args[])
{
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
89

// push some numbers onto the stack


for(int i=0; i<10; i++)
mystack1.push(i);
for(int i=10; i<20; i++)
mystack2.push(i);
// pop those numbers off the stack
System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());

System.out.println("Stack in mystack2:");

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


90

for(int i=0; i<10; i++)


System.out.println(mystack2.pop());
// these statements are not legal
// mystack1.tos = -2;
// mystack2.stck[3] = 100;
}
}

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Understanding static
91

¨ There will be times when we want to define a class member that will be
used independently of any object of that class. Normally, a class member
must be accessed only in conjunction with an object of its class.

¨ However, it is possible to create a member that can be used by itself,


without reference to a specific instance. To create such a member, precede
its declaration with the keyword static.

¨ When a member is declared static, it can be accessed before any objects of


its class are created, and without reference to any object. You can declare
both methods and variables to be static.

¨ The most common example of a static member is main( ). main( ) is


declared as static because it must be called before any objects exist.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


92

¨ Instance variables declared as static are, essentially, global variables. When


objects of its class are declared, no copy of a static variable is made. Instead,
all instances of the class share the same static variable.

¨ Methods declared as static have several restrictions:

• They can only call other static methods.


• They must only access static data.
• They cannot refer to this or super in any way. (The keyword super relates
to inheritance)

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


93

// Demonstrate static variables, methods, and blocks.


class UseStatic
{
static int a = 3;
static int b;
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static
{
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
94

System.out.println("Static block initialized.");


b = a * 4;
}
public static void main(String args[])
{
meth(42);
}
}

Static block initialized.


x = 42
a= 3
b = 12 Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
95

class StaticDemo
{
static int a = 42;
static int b = 99;
static void callme()
{
System.out.println("a = " + a);
}
}
class StaticByName
{
public static void main(String args[])

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


96

{
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}

Output:
a = 42
b = 99

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Introducing final
97

¨ 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. For example:

final int FILE_NEW = 1;


final int FILE_OPEN = 2;
final int FILE_SAVE = 3;
final int FILE_SAVEAS = 4;
final int FILE_QUIT = 5;

¨ Subsequent parts of your program can now use FILE_OPEN, etc., as if they
were constants, without fear that a value has been changed.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


98

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

¨ The keyword final can also be applied to methods, but its meaning is
substantially different than when it is applied to variables. This second
usage of final is described when inheritance is described.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Arrays Revisited
99

¨ Arrays are implemented as objects.

¨ Specifically, the size of an array that is, the number of elements that an
array can hold is found in its length instance variable. All arrays have this
variable, and it will always hold the size of the array.

// This program demonstrates the length array member.


class Length
{
public static void main(String args[])
{
int a1[] = new int[10];
int a2[] = {3, 5, 7, 1, 8, 99, 44, -10};

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


100

int a3[] = {4, 3, 2, 1};


System.out.println("length of a1 is " + a1.length);
System.out.println("length of a2 is " + a2.length);
System.out.println("length of a3 is " + a3.length);
}
}

Output:
length of a1 is 10
length of a2 is 8
length of a3 is 4

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Introducing Nested and Inner Classes
101

¨ It is possible to define a class within another class; such classes are known
as nested classes. The scope of a nested class is bounded by the scope of its
enclosing class. Thus, if class B is defined within class A, then B does not
exist independently of A.

¨ A nested class has access to the members, including private members, of


the class in which it is nested. However, the enclosing class does not have
access to the members of the nested class. A nested class that is declared
directly within its enclosing class scope is a member of its enclosing class.

¨ There are two types of nested classes: static and non-static. A static nested
class is one that has the static modifier applied. Because it is static, it must
access the members of its enclosing class through an object. That is, it
cannot refer to members of its enclosing class directly. Because of this
restriction, static nested classes are seldom used.
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
102

¨ The most important type of nested class is the inner class. An inner class is a
non-static nested class. It has access to all of the variables and methods of
its outer class and may refer to them directly in the same way that other
non-static members of the outer class do.

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


103

// Demonstrate an inner class.


class Outer
{
int outer_x = 100;
void test()
{
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner
{
void display()
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
104

{
System.out.println("display: outer_x = " +
outer_x);
}
}
}
class InnerClassDemo
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
} Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
105

¨ In the program, an inner class named Inner is defined within the scope of
class Outer. Therefore, any code in class Inner can directly access the
variable outer_x.

¨ An instance method named display( ) is defined inside Inner. This method


displays outer_x on the standard output stream.

¨ The main( ) method of InnerClassDemo creates an instance of class Outer


and invokes its test( ) method. That method creates an instance of class
Inner and the display( ) method is called.

¨ It is important to realize that an instance of Inner can be created only


within the scope of class Outer. The Java compiler generates an error
message if any code outside of class Outer attempts to instantiate class
Inner.
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
106

// This program will not compile.


class Outer
{
int outer_x = 100;
void test()
{
Inner inner = new Inner();
inner.display();
}
// this is an inner class
class Inner
{

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


107

int y = 10;
// y is local to Inner
void display()
{
System.out.println("display: outer_x = " + outer_x);
}
}
void showy()
{
System.out.println(y); // error, y not known here!
}
}

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


108

class InnerClassDemo
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
}
¨ Here, y is declared as an instance variable of Inner. Thus, it is not known
outside of that class and it cannot be used by showy( ).
¨ Although we have been focusing on inner classes declared as members
within an outer class scope, it is possible to define inner classes within any
block scope. For example, you can define a nested class within the block
defined by a method or even within the body of a for loop, as this next
program shows.
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
109

// Define an inner class within a for loop.


class Outer
{
int outer_x = 100;
void test()
{
for(int i=0; i<10; i++)
{
class Inner
{
void display()
{
System.out.println("display: outer_x = " + outer_x);
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
}
}
110

Inner inner = new Inner();


inner.display();
}
}
}
class InnerClassDemo
{
public static void main(String args[])
{
Outer outer = new Outer();
outer.test();
}
}
Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24
111

Output:
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100

Vikhyath K B, Dept of CSE, JSS ATE Bengaluru 560060 18/09/24


Vikhyath K B, Dept of CSE, JSS ATE
18/09/24 112
Bengaluru 560060

You might also like