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

2022 BCS306A OOC With Java Module 2 Notes

Uploaded by

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

2022 BCS306A OOC With Java Module 2 Notes

Uploaded by

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

Department of Computer Science and Business Systems

OOP with Java (BCS306A)


Notes: Module 2

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.

Methods and Classes: Overloading Methods, Objects as Parameters, Argument Passing,


Returning Objects, Recursion, Access Control, Understanding static, Introducing final,
Introducing Nested and Inner Classes.

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.

The General Form of a Class


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) {
// 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.

Ramesh Babu N, Page 2 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
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.

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 */

//Definition of class Box (user defined data type)


class Box {
double width;
double height;
double depth;
}

// This class declares an object of type Box.


class BoxDemo {
public static void main(String args[]) {
//Object Creation
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 */


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

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

The output produced by this program is shown here:


Volume is 3000.0
Volume is 162.0

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.

Ramesh Babu N, Page 3 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
Box mybox = new Box(); // create a Box object called mybox

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.

Box mybox = new Box();

mybox will be referencing newly created object.

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

A Closer Look at new


The new operator dynamically allocates memory for an object.
It has this general form:

class-var = new classname( );


Here, class-var is a variable of the class type being created.
The classname is the name of the class that is being instantiated.
The class name followed by parentheses specifies the constructor for the class.

If new is not able to allocate memory for an object because insufficient memory exists, then
a run-time exception will occur.

Ramesh Babu N, Page 4 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
Assigning Object Reference Variables
When you assign one object reference variable to another object reference variable, you are
not creating a copy of the object, you are only making a copy of the reference.
For example
Box b1 = new Box();
Box b2 = b1;

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.

Adding a Method to the Box Class


Returning a Value and Adding a Method That Takes Parameters
Methods define the interface to most classes. Use methods to access the instance variables
defined by the class (data hiding and abstraction). You can also define methods that are used
internally by the class itself.
Ramesh Babu N, Page 5 of 26
Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)

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;

// compute and return volume


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

// sets dimensions of box w, h, d are parameters


void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
}

//Demo Class Definition


class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
double vol;

// assign values to mybox1's instance variables


mybox1.setDim(10, 20, 15); //10, 20, 15 are
arguments

// get volume of first box


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

As you can see, the setDim( ) method is used to set the dimensions of each box. For example,
when

mybox1.setDim(10, 20, 15);


is executed, 10 is copied into parameter w, 20 is copied into h, and 15 is copied into d. Inside
setDim( ) the values of w, h, and d are then assigned to width, height, and depth, respectively.

Ramesh Babu N, Page 6 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
Constructors
Java allows objects to initialize themselves when they are created.
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.
 The constructor is automatically called immediately after the object is created, before
the new operator completes.
 Constructors have no return type, not even void.

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;

// This is the constructor for Box.


Box() {
System.out.println("Zero argument Constructor
called.");
width = 10;
height = 10;
depth = 10;
}

// This is the constructor for Box.


Box(double w, double h, double d) {
System.out.println("Parameterized Constructor
called.");
width = w;
height = h;
depth = d;
}

// compute and return volume


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

Ramesh Babu N, Page 7 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
//Demo class denitition
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box(3, 6, 9);
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);
}
}

When this program is run, it generates the following results:


Zero argument Constructor called.
Parameterized Constructor called.
Volume is 1000.0
Volume is 162.0

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.

The this Keyword and Instance Variable Hiding


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.

To access members, use dot operator. this.member


Example:
// A redundant use of this.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}

this.width refers to width of an object on which the above constructor is called.

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:

Ramesh Babu N, Page 8 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}

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:

protected void finalize( )


{
// finalization code here
}

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

// Push an item onto the stack


void push(int item) {
if(tos==9)
System.out.println("Stack is full.");
else
stck[++tos] = item;
}
Ramesh Babu N, Page 9 of 26
Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)

// Pop an item from the stack


int pop() {
if(tos < 0) {
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();

//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:");
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

Ramesh Babu N, Page 10 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
Methods and Classes
Overloading Methods
Methods are said to be overloaded, when two or more methods within the same class has
the same name, with different parameters.

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.

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

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

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

This program generates the following output:


No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of ob.test(123.25): 15190.5625
Ramesh Babu N, Page 11 of 26
Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
When an overloaded method is called, Java looks for a match between the arguments used
to call the method and the method’s parameters. However, this match need not always be
exact. In some cases, Java’s automatic type conversions can play a role in overload resolution.

Example: Overloaded Method call resolution


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

This program generates the following output:


No parameters
a and b: 10 20
Inside test(double) a: 88
Inside test(double) a: 123.2

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;

Ramesh Babu N, Page 12 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
// 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; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}

// constructor used when cube is created


Box(double len) {
width = height = depth = len;
}

// 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);
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:
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.

Ramesh Babu N, Page 13 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
Using Objects as Parameters
In Java, objects can be passed to methods.

Example:
// 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) {
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));


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

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

Ramesh Babu N, Page 14 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
A Closer Look at Argument Passing
Types:
a. Call by value
b. Call by reference

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.

Example: Call by value


// 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[]) {
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

Example: Call by reference


// Objects are passed by reference.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}

Ramesh Babu N, Page 15 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
// pass an object
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}

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

Ramesh Babu N, Page 16 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)

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

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

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

Ramesh Babu N, Page 17 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
Output:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120

Working of above program:


When you compute the factorial of 3, the first call to fact( ) will cause a second call to be
made with an argument of 2. This invocation will cause fact( ) to be called a third time with
an argument of 1. This call will return 1, which is then multiplied by 2 (the value of n in the
second invocation). This result (which is 2) is then returned to the original invocation of
fact( ) and multiplied by 3 (the original value of n). This yields the answer, 6.

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];
}

// display array -- recursively


void printArray(int i) {
if(i==0)
return;
else
printArray(i-1);
System.out.println("[" + (i-1) + "] " + values[i-1]);
}
}

class Recursion2 {
public static void main(String args[]) {
RecTest ob = new RecTest(10);
int i;

Ramesh Babu N, Page 18 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
for(i=0; i<10; i++)
ob.values[i] = 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

Introducing Access Control


Access specifier determines the access control of a member.

Java’s access specifiers are public, private, protected and default.


public
members can be accessed by any other code.

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.

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


Example: declaring access specifiers
public int i;
private double j;
private int myMethod(int a, char b) { // ...

Ramesh Babu N, Page 19 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
Example: Access Specifiers
/* This program demonstrates the difference between public and
private.
*/
class Test {
int a; // default access

public int b; // public access


private int c; // private access

// methods to access c
void setc(int i) { // set c's value
c = i;
}

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;

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

Example: Stack with access specifiers


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

Ramesh Babu N, Page 20 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
// 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;
}
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


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

// these statements are not legal as the members are


// declared private
// mystack1.tos = -2;
// mystack2.stck[3] = 100;
}
}

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.

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.

To initialise static data members (class variables) declare a static block that gets executed
exactly once, when the class is first loaded.

Example: Declaring and initialising static variables


// 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 {
System.out.println("Static block initialized.");
b = a * 4;
}

public static void main(String args[]) {


meth(42);
}
}
Output:
Static block initialized.
x = 42
a = 3
b = 12

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.

Static member access:


Static methods and variables can be used independently of any object.

Syntax: classname.static_method() and classname.static_variable

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;

static void callme() {


System.out.println("a = " + a);
}
}

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

Here is the output of this program:


a = 42
b = 99

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

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

Ramesh Babu N, Page 23 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
Note: length reflects the number of elements that the array is designed to hold

Example: Improved Stack, check stack overflow using length


// Push an item onto the stack
void push(int item) {
if(tos==stck.length-1) // use length member
System.out.println("Stack is full.");
else
stck[++tos] = item;
}

Introducing Nested and Inner Classes


Nested Classes: defining a class within another class.

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.

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.

non-static nested class (also called inner class)


An inner class 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.

Example: Inner class


// 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() {
System.out.println("display: outer_x = " + outer_x);
}
}
}

Ramesh Babu N, Page 24 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}

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.

Example: // 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 {
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!
}
}

Ramesh Babu N, Page 25 of 26


Dept. of CS & BS, KSSEM
OOP with Java(BCS306A)
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( ).

Textbook:
1. Java: The Complete Reference, Twelfth Edition, by Herbert Schildt, November 2021,
McGraw-Hill, ISBN: 9781260463422

Ramesh Babu N, Page 26 of 26


Dept. of CS & BS, KSSEM

You might also like