Java Module-2
Java Module-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.
classes contain code and data. A class’ code defines the interface to its data.
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.
¨ 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
¨ 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.
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
}
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.
¨ 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.
¨ This statement combines the two steps just described. It can be rewritten
like this to show each step more clearly:
¨ 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.
¨ Here, b1 and b2 are not referring to the separate objects. They refer to the
same object.
¨ 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:
¨ Here, b1 has been set to null, but b2 still points to the original object.
Classes usually consist of two things: instance variables and methods. The
Java gives methods so much power and flexibility.
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;
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;
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
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;
vol = mybox1.volume();
¨ The value of mybox1.volume( ) is 3,000 and this value then is stored in vol.
¨ 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.
¨ 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:
¨ 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
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);
}
}
¨ Java allows objects to initialize themselves when they are created. This
automatic initialization is performed through the use of a constructor.
¨ Constructors look a little strange because they have no return type, not
even void.
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
¨ 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.
¨ As we know, it is illegal in Java to declare two local variables with the same
name inside the same or enclosing scopes.
¨ 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
¨ 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
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:");
¨ 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
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
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
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);
}
}
Output:
ob1 == ob2: true
ob1 == ob3: false
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
¨ In general, there are two ways that a computer language can pass an
argument to a subroutine.
¨ 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.
¨ As you will see, Java uses both approaches, depending upon what is
passed.
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
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
}
}
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));
}
}
Output:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
¨ 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.
¨ 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.
¨ 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.
public int i;
private double j;
private int myMethod(int a, char b)
{ // ...
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;
ob.setc(100); // OK
{ /* 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. */
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
System.out.println("Stack in mystack2:");
¨ 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.
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[])
{
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
Output:
a = 42
b = 99
¨ Subsequent parts of your program can now use FILE_OPEN, etc., as if they
were constants, without fear that a value has been changed.
¨ 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.
¨ 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.
Output:
length of a1 is 10
length of a2 is 8
length of a3 is 4
¨ 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.
¨ 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.
{
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.
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!
}
}
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
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