2022 BCS306A OOC With Java Module 2 Notes
2022 BCS306A OOC With Java Module 2 Notes
Prepared by,
Ramesh Babu N,
Associate Professor,
Dept. of CS & BS,
KSSEM
OOP with Java(BCS306A)
Contents
Introducing Classes ............................................................................................................... 2
Class Fundamentals ........................................................................................................... 2
The General Form of a Class .............................................................................................. 2
A Simple Class ................................................................................................................... 3
Declaring Objects .............................................................................................................. 4
A Closer Look at new ......................................................................................................... 4
Assigning Object Reference Variables ................................................................................ 5
Introducing Methods ......................................................................................................... 5
Adding a Method to the Box Class ..................................................................................... 5
Returning a Value and Adding a Method That Takes Parameters....................................... 5
Constructors...................................................................................................................... 7
The this Keyword and Instance Variable Hiding ................................................................. 8
Garbage Collection ............................................................................................................ 9
The finalize( ) Method ....................................................................................................... 9
A Stack Class...................................................................................................................... 9
Methods and Classes .......................................................................................................... 11
Overloading Methods ...................................................................................................... 11
Overloading Constructors ............................................................................................ 12
Using Objects as Parameters ........................................................................................... 14
Copy Constructor ............................................................................................................ 14
A Closer Look at Argument Passing.................................................................................. 15
Returning Objects............................................................................................................ 16
Recursion ........................................................................................................................ 17
Introducing Access Control .............................................................................................. 19
Understanding static ....................................................................................................... 21
Introducing final .............................................................................................................. 23
Arrays Revisited............................................................................................................... 23
Introducing Nested and Inner Classes .............................................................................. 24
Syllabus
Introducing Classes: Class Fundamentals, Declaring Objects, Assigning Object Reference
Variables, Introducing Methods, Constructors, The this Keyword, Garbage Collection.
Chapter 6, 7
Ramesh Babu N, Page 1 of 26
Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
Introducing Classes
The class is at the core of Java. It is the logical construct upon which the entire Java language
is built because it defines the shape and nature of an object. Any concept you wish to
implement in a Java program must be encapsulated within a class.
Class Fundamentals
A class is that it defines a new data type. Once defined, this new type can be used to create
objects of that type. Thus, a class is a template for an object, and an object is an instance of a
class.
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
type instance-variable1;
type can be inbuilt or user defined.
instance-variable valid Java identifier
type methodnameN(parameter-list) {
// body of method
}
type: return type of the method
methodname (): valid Java identifier
parameter-list: list of formal arguments
body of method: one or more statements
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.
The data for one object is separate and unique from the data for another. class declaration
and the implementation of the methods are stored in the same place and not defined
separately.
A Simple Class
/* A program that uses the Box class. Call this file
BoxDemo.java */
Box class that defines three instance variables: width, height, and depth. Box class defines a
new type of data. To actually create a Box object, use the following statement.
mybox reference variable points to newly created Box object. Each time you create an
instance of a class, you are creating an object that contains its own copy of each instance
variable defined by the class. Thus, every Box object will contain its own copies of the instance
variables width, height, and depth.
To access these variables and methods on objects, you will use the dot (.) operator. The dot
operator links the name of the object with the name of an instance variable.
mybox.width = 100; //copies 100 to width of object referenced by mybox
Declaring Objects
To create object(s) of a class,
a. You must declare a variable of the class type. This variable can refer to an object.
b. Acquire an actual, physical copy of the object and assign it to that variable using new
operator (allocates memory dynamically and returns a reference to it). This reference
is then stored in the variable.
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
If new is not able to allocate memory for an object because insufficient memory exists, then
a run-time exception will occur.
After this fragment executes, b1 and b2 will both refer to the same object.
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.
Introducing Methods
Classes usually consist of two things: instance variables and methods. 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. This can be primitive type, user
defined or void if the method does not return a value.
name can be any legal identifier other than those already used by other items within the
current scope.
parameter-list is a sequence of type and identifier pairs separated by commas. If the method
has no parameters, then the parameter list will be empty.
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.
While some methods don’t need parameters, most do. You can use a parameterized method
to improve the Box class.
An argument is a value that is passed to a method when it is invoked.
A parameter is a variable defined by a method that receives a value when the method is
called.
Example:
//Box class definition
class Box {
double width;
double height;
double depth;
As you can see, the setDim( ) method is used to set the dimensions of each box. For example,
when
Types of Constructors:
Zero argument constructor
Constructor does not accept any parameters.
Parameterized constructor
Constructor accepts one or more parameters.
Example:
/* Here, Box uses a constructor to initialize the dimensions of
a box. */
//Box class Definition
class Box {
double width;
double height;
double depth;
When you do not explicitly define a constructor for a class, then Java creates a default
constructor for the class. The default constructor automatically initializes all instance
variables to zero.
When a local variable in a method has the same name as an instance variable, the local
variable hides the instance variable. this lets you refer directly to the object, you can use it to
resolve any name space collisions that might occur between instance variables and local
variables.
For example, here is another version of Box( ), which uses width, height, and depth for
parameter names and then uses this to access the instance variables by the same name:
Garbage Collection
In C++, dynamically allocated objects must be manually released by use of a delete operator.
In Java, deallocation is automatic and is handled by garbage collector. 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 by garbage collector.
Garbage collection only occurs sporadically (if at all) during the execution of your program.
The finalize( ) Method
Java provides a mechanism to define specific actions (release resources held by an object)
that will occur when an object is just about to be reclaimed by the garbage collector.
To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls
that method whenever it is about to recycle an object of that class. Right before an asset is
freed, the Java run time calls the finalize( ) method on the object. The general form:
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
A Stack Class
A stack stores data using first-in, last-out ordering. 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.
// This class defines an integer stack that can hold 10 values.
class Stack {
int stck[] = new int[10];
int tos;
// Initialize top-of-stack
Stack() {
tos = -1;
}
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
}
}
Output:
Stack in mystack1:
9
8
7
6
5
4
3
2
1
0
Stack in mystack2:
19
18
17
16
15
14
13
12
11
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.
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
class Overload {
public static void main(String args[]) {
Method overloading supports polymorphism because it is one way that Java implements
the “one interface, multiple methods” paradigm.
Overloading Constructors
Java supports overloading of constructor methods.
Example:
/* Here, Box defines three constructors to initialize
the dimensions of a box various ways.
*/
class Box {
double width;
double height;
double 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);
double vol;
Output:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0
As you can see, the proper overloaded constructor is called based upon the parameters
specified when new is executed.
Example:
// Objects may be passed to methods.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
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);
Output:
ob1 == ob2: true
ob1 == ob3: false
Copy Constructor
A constructor that takes an object and initialises the current object is called Copy Constructor.
Example:
…
// 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;
}
…
…
Box mybox1 = new Box(10, 20, 15);
Box myclone = new Box(mybox1); // create copy of mybox1
…
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.
Passing a primitive type is by call by value.
Call by reference
In this approach, a reference to an argument is passed to the parameter. Inside the
subroutine, this reference is used to access the actual argument specified in the call. Changes
made to the parameter will affect the argument used to call the subroutine.
Objects are passed to methods are by reference.
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
ob.meth(a, b);
Output:
a and b before call: 15 20
a and b after call: 15 20
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
ob.meth(ob);
Output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10
As a point of interest, when an object reference is passed to a method, the reference itself
is passed by use of call-by-value. However, since the value being passed refers to an object,
the copy of that value will still refer to the same object that its corresponding argument does.
Note: 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.
Returning Objects
A method can return any type of data, including class types that you create.
Example:
// Returning an object.
class Test {
int a;
Test(int i) {
a = i;
}
Test incrByTen() {
Test temp = new Test(a+10);
return temp;
}
}
class RetOb {
public static void main(String args[]) {
ob2 = ob1.incrByTen();
System.out.println("ob1.a: " + ob1.a);
System.out.println("ob2.a: " + ob2.a);
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
As you can see, each time incrByTen( ) is invoked, a new object is created, and a reference
to it is returned to the calling routine.
Recursion
Java supports recursion. Recursion is the process of defining something in terms of itself.
A method that calls itself is said to be recursive.
Example: Factorial
// 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;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
When a method calls itself, new local variables and parameters are allocated storage
on the stack, and the method code is executed with these new variables from the start.
As each recursive call returns, the old local variables and parameters are removed from
the stack, and execution resumes at the point of the call inside the method.
Recursive versions of many routines may execute a bit more slowly than the iterative
equivalent because of the added overhead of the additional function calls.
Advantage to recursive methods is that they can be used to create clearer and simpler
versions of several algorithms than can their iterative relatives.
Caution:
When writing recursive methods, you must have an if statement somewhere to force the
method to return without the recursive call being executed.
Example:
// Another example that uses recursion.
class RecTest {
int values[];
RecTest(int i) {
values = new int[i];
}
class Recursion2 {
public static void main(String args[]) {
RecTest ob = new RecTest(10);
int i;
ob.printArray(10);
}
}
Output:
[0] 0
[1] 1
[2] 2
[3] 3
[4] 4
[5] 5
[6] 6
[7] 7
[8] 8
[9] 9
private
members can only be accessed by other members of its class.
protected
members will be private to class and can be accessed in child classes only (same and different
packages).
default
member of a class is public within its own package, but cannot be accessed outside of its
package.
// methods to access c
void setc(int i) { // set c's value
c = i;
}
class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
// Initialize top-of-stack
Stack() {
tos = -1;
}
class TestStack {
public static void main(String args[]) {
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
Understanding static
Static data members are used to define a class member, that will be used independently of
any object of that class.
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.
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
Ramesh Babu N, Page 21 of 26
Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
share the same static variable.
To initialise static data members (class variables) declare a static block that gets executed
exactly once, when the class is first loaded.
static {
System.out.println("Static block initialized.");
b = a * 4;
}
As soon as the UseStatic class is loaded, all of the static statements are run.
a. First, a is set to 3
b. Then the static block executes, which prints a message and then initializes b to a * 4
or 12. Then main( ) is called, which calls meth( ), passing 42 to x.
c. The three println( ) statements refer to the two static variables a and b, as well as to
the local variable x.
Here, classname is the name of the class in which the static method is declared.
This is how Java implements a controlled version of global methods and global variables.
Ramesh Babu N, Page 22 of 26
Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
Example: Accessing static variables and methods
class StaticDemo {
static int a = 42;
static int b = 99;
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
Introducing final
To create constants in Java declare variable as final. All the final variables must be initialised.
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 they are constants.
Variables declared as final do not occupy memory on a per-instance basis.
It is a common coding convention to choose all uppercase identifiers for final variables.
Arrays Revisited
All arrays have length, and it will always hold the size of the array.
Example:
// 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};
int a3[] = {4, 3, 2, 1};
The scope of a nested class is bounded by the scope of its enclosing class.
(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 enclosing class.
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. It is also possible to declare a nested class that is local to a block.
void test() {
Inner inner = new Inner();
inner.display();
}
Output:
display: outer_x = 100
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.
You can create an instance of Inner outside of Outer by qualifying its name with Outer, as in
Outer.Inner.
An inner class has access to all of the members of its enclosing class, but the reverse is not
true.
Members of the inner class are known only within the scope of the inner class and may not
be used by the outer class.
void test() {
Inner inner = new Inner();
inner.display();
}
void display() {
System.out.println("display: outer_x = " + outer_x);
}
}
void showy() {
System.out.println(y); // error, y not known here!
}
}
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( ).
Textbook:
1. Java: The Complete Reference, Twelfth Edition, by Herbert Schildt, November 2021,
McGraw-Hill, ISBN: 9781260463422