0% found this document useful (0 votes)
11 views29 pages

Java M2 Notes

Module 2 of the Object Oriented Programming with JAVA course focuses on classes, their fundamentals, and how to create and use objects in Java. It explains the structure of a class, the process of declaring and initializing objects, and the role of methods and constructors in managing object behavior and properties. Key concepts include instance variables, method definitions, and the use of parameters in methods to enhance functionality.

Uploaded by

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

Java M2 Notes

Module 2 of the Object Oriented Programming with JAVA course focuses on classes, their fundamentals, and how to create and use objects in Java. It explains the structure of a class, the process of declaring and initializing objects, and the role of methods and constructors in managing object behavior and properties. Key concepts include instance variables, method definitions, and the use of parameters in methods to enhance functionality.

Uploaded by

dhanush21506
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object Oriented Programming with JAVA(BCS306A) Module-2

Module - 2
Chap1: 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.

Class Fundamentals:
• Class defines a new data type. Once defined, this new type can be used to create objects
of that type.
• A class is a template for an object, and an object is an instance of a class.

The General Form of a Class:


• When you define a class, you declare its exact form and nature. You do this by specifying
the data that it contains and the code that operates on that data.
• 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 methodnameN(parameter-list) {
// body of method
} }
• 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.
• 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.

Mrs. Swathi C S, Asst professor, SVIT, P a g e 1 | 29


Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

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

• A class defines a new type of data. In this case, the new data type is called Box so use this
name to declare objects of type Box.
• A class declaration only creates a template it does not create an actual object
Box mybox = new Box( ); // create a Box object called mybox

• After this statement executes, mybox will be an instance of [Link], 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, you will use the dot (.) operator. The dot operator links the
name of the object with the name of an instance variable.
• For example, to assign the width variable of mybox the value 100, you would use the
following statement:
[Link] = 100;
class Box {
double width;
double height;
double depth;
}

• The complete program that uses the Box class as follows:


class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
[Link] = 10;
[Link] = 20;
[Link] = 15;
// compute volume of box
Mrs. Swathi C S, Asst professor, SVIT, P a g e 2 | 29
Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

vol = [Link] * [Link] * [Link];


[Link]("Volume is " + vol);
} }

Declaring Objects
• When you create a class, you are creating a new data type. However, obtaining objects of
a class is a two-step process.
• First, you must 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, you must acquire an actual, physical copy of the object and assign it to that
variable. You 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 reference is, more or less, the address in memory of the object allocated by new.
• This reference is then stored in the variable. Thus, in Java, all class objects must be
dynamically allocated.
Box mybox = new Box( );
• This statement combines the two steps as,
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. The next line
allocates an actual object and assigns a reference to it to mybox.
• After the second line executes, you can use mybox as if it were a Box object. But in reality,
mybox simply holds the memory address of the actual Box object. The effect of these two
lines of code is depicted in Figure 6.1

Mrs. Swathi C S, Asst professor, SVIT, P a g e 3 | 29


Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

• The new operator dynamically allocates memory for an object. In the context of an
assignment, 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. A
constructor defines what occurs when an object of a class is created.
• Constructors are an important part of all classes and have many significant [Link]
allocates memory for an object during runtime.
• The advantage of this approach is that your program can create as many or as few objects
as it needs during the execution of your program.
• However, since memory is finite, it is possible that new will not be able to allocate
memory for an object because insufficient memory exists. If this happens, a run-time
exception will occur.
• A class creates a new data type that can be used to create objects. That is, a class creates
a logical framework that defines the relationship between its members.
• When user declare an object of a class, you are creating an instance of that class. Thus, a
class is a logical construct. An object has physical reality.

Assigning Object Reference Variables


• Object reference variables act differently when an assignment takes place. Box b1 = new
Box( );
Box b2 = b1;
• After this fragment executes, b1 and b2 will both refer to the same object.
• The assignment of b1 to b2 did not allocate any memory or copy any part of the original
object. It simply makes b2 refer to the same object as does b1.
• Thus, any changes made to the object through b2 will affect the object to which b1 is
referring, since they are the same object. This situation is depicted here:

• Although b1 and b2 both refer to the same object, they are not linked in any other way.
Box b1 = new Box( );
Box b2 = b1;
// ...
b1 = null;

Mrs. Swathi C S, Asst professor, SVIT, P a g e 4 | 29


Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

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

Introducing methods
• 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. This can be any legal identifier other than those already used by
other items within the current scope.
• The parameter-list is a sequence of type and identifier pairs separated by commas.
Parameters are essentially variables that receive the value of the arguments passed to the
method when it is called.
• 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


• Methods are used to access the instance variables defined by the class. In fact, methods
define the interface to most classes.
• This allows the class implementor to hide the specific layout of internal data structures
behind cleaner method abstractions.
• In addition to defining methods that provide access to data, you can also define methods
that are used internally by the class itself.
• Example adding a method to the Box class as follows:
class Box {
double width;
double height;
double depth;
// display method for volume of a box
void volume() {
[Link]("Volume is ");
[Link](width * height * depth);
Mrs. Swathi C S, Asst professor, SVIT, P a g e 5 | 29
Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

} }
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
// assign values to mybox1's instance variables
[Link] = 10;
[Link] = 20;
[Link] = 15;
// display volume of first box
[Link]();
} }
This program generates the following output:
Volume is 3000.0
Volume is 162.0

• Here, [Link](); invokes the volume( ) method on mybox1. That is, it calls
volume( ) relative to the mybox1 object, using the object’s name followed by the dot
operator.
• Thus, the call to [Link]( ) displays the volume of the box defined by mybox1,
• Inside the volume( ) method the instance variables width, height, and depth are referred
to directly, without preceding them with an object name or the dot operator.
• When a method uses an instance variable that is defined by its class, it does so directly,
without explicit reference to an object and without use of the dot operator.
• A method is always invoked relative to some object of its class. Once this invocation has
occurred, the object is known.

Returning a Value

• A better way to implement volume( ) is to have it compute the volume of the box and return
the result to the caller. The following example
class Box {
double width;
double height;
double depth;
// compute and return volume

Mrs. Swathi C S, Asst professor, SVIT, P a g e 6 | 29


Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

double volume() {
return width * height * depth;
} }
class BoxDemo4 {
public static void main(String args[]) {

Box mybox1 = new Box();

[Link] = 10;
[Link] = 20;
[Link] = 15;
double vol =
[Link]();
[Link]("Volume is " + vol);
}}
• When volume( ) is called, it is put on the right side of an assignment statement. On the left
is a variable, in this case vol, that will receive the value returned by volume( ).
• Thus, after vol = [Link]( ); executes, the value of [Link]( ) 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.
Adding a Method That Takes Parameters

• 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
int square( )
{
return 10 * 10;
}

Mrs. Swathi C S, Asst professor, SVIT, P a g e 7 | 29


Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

• While this method return the value of 10 squared, its use is very limited.
However, if you modify the method so that it takes a parameter then you can make square(
) much more useful.
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
• In the first call to square( ), the value 5 will be passed into parameter i.
• In the second call, I will receive the value 9.
• The third invocation passes the value of y, which is 2 in this example.
• As these examples show, square( ) is able to return the square of whatever data it is passed.
• A parameter is a variable defined by a method that receives a value when the method is
called. For example, in square( ), i is a parameter.
• An argument is a value that is passed to a method when it is Invoked. For example,
square(100) passes 100 as an argument. Inside square( ), the parameter i receives that value.
• Thus, a better approach to setting the dimensions of a box is to create a method that takes
the dimensions of a box in its parameters and sets each instance variable appropriately.
• This concept is implemented by the following program:
// This program uses a parameterized method.
class Box {
double width;
double height;
double depth;
double volume( ) {
return width * height * depth;

Mrs. Swathi C S, Asst professor, SVIT, P a g e 8 | 29


Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

}
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();
[Link](10, 20, 15);

double vol [Link]();


[Link]("Volume is " + vol);
}}

• The setDim( ) method is used to set the dimensions of each box. For example, when
[Link](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.

Constructors
• It can be tedious to initialize all of the variables in a class each time an instance is created.
• Because the requirement for initialization is so common, 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 not have return type, not even void. This is because the implicit return type
of a class’ constructor is the class type itself.
• It is the constructor’s job to initialize the internal state of an object so that the code creating
an instance will have a fully initialized, usable object immediately.
• There are 2 types of constructor: Default and parameterized constructor.
• For Default constructor, dimensions of a box are automatically initialized when an object
is constructed. To do so, replace setDim( ) with a constructor as follows:

Mrs. Swathi C S, Asst professor, SVIT, P a g e 9 | 29


Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

class Box {
double width;
double height;
double depth;
Box( ) {
[Link]("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
double volume() {
return width * height * depth;
}}
class BoxDemo6 {
public static void main(String args[ ]) {
Box mybox1 = new Box( );
double vol = [Link]();
[Link]("Volume is " + vol);
• When this program is run, it generates the following results:
Constructing Box
Volume is 1000.0
• mybox1 was initialized by the Box( ) constructor when it was created. Since the
constructor gives all boxes the same dimensions, 10 by 10 by 10, mybox1 will have the
same volume.
• When you allocate an object, you use the following general form:
class-var = new classname ( );
• The constructor for the class is being called by specifying class with parenthesis. Thus, in
the line Box mybox1 = new Box();
• new Box( ) is calling the Box( ) constructor new .
• When you do not explicitly define a constructor for a class, then Java creates a default
constructor for the class.
• When using the default constructor, all noninitialized instance variables will have their
default values, which are zero, null, and false, for numeric types, reference types, and
boolean, respectively.

Mrs. Swathi C S, Asst professor, SVIT, P a g e 10 | 29


Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

Parameterized Constructors
• The Box( ) constructor in the preceding example does initialize a Box object, it is not very
useful as all boxes won’t have the same dimensions.
• So to construct Box objects of various dimensions add parameters to the constructor called
parameterized constructor.
• For example, the following version of Box defines a parameterized constructor that sets the
dimensions of a box as specified by those parameters.
class Box {
double width;
double height;
double depth;

Box(double w, double h, double d) {


width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}}
class BoxDemo7 {
public static void main(String args[ ]) {
Box mybox1 = new Box(10, 20, 15);
Double vol = [Link]( );
[Link]("Volume is " + vol);
}}

• The output from this program is shown here:


Volume is 3000.0

• Each object is initialized as specified in the parameters to its constructor. For example, in
the following line, Box mybox1 = new Box(10, 20, 15).
• The values 10, 20, and 15 are passed to the Box( ) constructor when new creates the object.
Thus, mybox1’s copy of width, height, and depth will contain the values 10, 20, and 15.
respectively.

Mrs. Swathi C S, Asst professor, SVIT, P a g e 11 | 29


Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

The this keyword


• Sometimes a method will need to refer to the object that invoked it. To allow this, Java
defines the this keyword.
• this can be used inside any method to refer to the current object.
• That is, this is always a reference to the object on which the method was invoked.
• You can use this anywhere a reference to an object of the current class’ type is permitted.
• For Example consider the following version of Box( ):
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double width, double height, double depth) {
[Link] = width;
[Link] = height;
[Link] = depth;
}
double volume( ) {
return width * height * depth;
}}
class BoxDemo7 {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
double vol = [Link]( );
[Link]("Volume is " + vol);
}}
Uses of this:
• To overcome shadowing or instance variable hiding.
• To call an overload constructor Instance Variable Hiding
• 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.
Mrs. Swathi C S, Asst professor, SVIT, P a g e 12 | 29
Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

• 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) {
[Link] = width;
[Link] = height;
[Link] = depth;
}

Garbage Collection
• Since objects are dynamically allocated by using the new operator, such objects are
destroyed and their memory released for later reallocation.
• Java takes a different approach, it handles deallocation 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.
• There is no explicit need to destroy objects as in C++.Garbage collection only occurs
sporadically (if at all) during the execution of your program.
• It will not occur simply because one or more objects exist that are no longer used.
• Classification based on 3 generation of java heap: Young, old and permanent Generation.

[Link] Generation
This is where new objects are allocated and aged.
The Young Generation is further divided into three parts: Eden space, Survivor 1 space, and
Survivor 2 space. When the Young Generation fills up, a minor garbage collection occurs.
[Link] or Tenured Generation
This is where objects that have survived multiple garbage collection cycles in the Young
Generation are moved. It's designed for objects with a longer lifecycle.
[Link] Generation
This part of the heap holds metadata such as classes and methods, which do not change frequently.
This generation is only present in JVMs before Java 8.
Mrs. Swathi C S, Asst professor, SVIT, P a g e 13 | 29
Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

CHAPTER 2: METHODS AND CLASSES

Overloading Methods
• 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.
• For example:

class OverloadDemo {
void test() {
[Link]("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
[Link]("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
[Link]("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
[Link]("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()
[Link]();
[Link](10);
[Link](10, 20);
result = [Link](123.25);

Mrs. Swathi C S, Asst professor, SVIT, P a g e 14 | 29


Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

[Link]("Result of [Link](123.25): " + result);


}
}
This program generates the following output:
No parameters
a: 10
a and b: 10 20
double a: 123.25
Result of [Link](123.25): 15190.5625

• 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.
• For example, consider the following program:

// Automatic type conversions apply to overloading.


class OverloadDemo {
void test() {
[Link]("No parameters");
}
// Overload test for two integer parameters.
void test(int a, int b) {
[Link]("a and b: " + a + " " + b);
}
// overload test for a double parameter
void test(double a) {
[Link]("Inside test(double) a: " + a);
}
}
class Overload {
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
int i = 88;
[Link]();
[Link](10, 20);
[Link](i); // this will invoke test(double)
[Link](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

Mrs. Swathi C S, Asst professor, SVIT, P a g e 15 | 29


Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

Inside test(double) a: 123.2

• When test( ) is called with an integer argument inside Overload, no matching method
is found.
• However, Java can automatically convert an integer into a double, and this conversion
can be used to resolve the call.
• Therefore, after test(int) is not found, Java elevates i to double and then calls
test(double), if test(int) had been defined, it would have been called instead. Java will
employ its automatic type conversions only if no exact match is found.
• Method overloading supports polymorphism because it is one way that Java implements
the “one interface, multiple methods” paradigm.
• here is no rule stating that overloaded methods must relate to one another. However,
from a stylistic point of view, method overloading implies a relationship.

Overloading Constructors
• In addition to overloading normal methods, user can also overload constructor methods.
• Example of Box:
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;
}
// 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[]) {
Mrs. Swathi C S, Asst professor, SVIT, P a g e 16 | 29
Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

// create boxes using the various constructors


Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;

vol = [Link]();
[Link]("Volume of mybox1 is " + vol);
// get volume of second box

vol = [Link]();
[Link]("Volume of mybox2 is " + vol);
// get volume of cube
vol = [Link]();
[Link]("Volume of mycube is " + vol);
}
}
The output produced by this program is shown here:
Volume of mybox1 is 3000.0
Volume of mybox2 is -1.0
Volume of mycube is 343.0

Using Objects as Parameters

• User can pass objects to methods. For example, consider the following short program:

class Test
{
int a;
void meth(Test o)
{
o.a*=2;
} }

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

Test ob1 = new Test( );


ob1.a=10;
[Link]("ob1 is: " + [Link](ob1));
}
}
Output:
Ob1=10;
Mrs. Swathi C S, Asst professor, SVIT, P a g e 17 | 29
Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

Argument Passing

• 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.
• 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:

// 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;
[Link]("a and b before call: " +a + " " + b);
[Link](a, b);
[Link]("a and b after call: " + a + " " + b);
}
}
The output from this program is shown here:
a and b before call: 15 20
a and b after call: 15 20

• When you pass an object to a method, the situation changes , because objects are passed
by what is effectively call-by-reference.
• Thus, when you pass this reference to a method, the parameter that receives it will refer
to the same object as that referred to by the argument.

Mrs. Swathi C S, Asst professor, SVIT, P a g e 18 | 29


Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

• This effectively means that objects are passed to methods by use of call-by-reference.
• Changes to the object inside the method do affect the object used as an argument.
• For example, consider the following program:

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

class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
[Link]("ob.a and ob.b before call: " + ob.a + " " + ob.b);
[Link](ob);
[Link]("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}
}
This program generates the following output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after call: 30 10

Returning Objects

• 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() {
Test temp = new Test(a+10);
return temp;
Mrs. Swathi C S, Asst professor, SVIT, P a g e 19 | 29
Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

}
}

class RetOb {
public static void main(String args[]) {
Test ob1 = new Test(2);
Test ob2;
ob2 = [Link]();
[Link]("ob1.a: " + ob1.a);
[Link]("ob2.a: " + ob2.a);
}
}
The output generated by this program is shown here:
ob1.a: 2
ob2.a: 12

Recursion

• 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.
• The classic example of recursion is the computation of the factorial of a number. The
factorial of a number N is the product of all the whole numbers between 1 and N.
• For example, 3 factorial is 1 × 2 × 3, or 6. Here is how a factorial can be computed by use
of a recursive method:

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();
[Link]("Factorial of 3 is " + [Link](3));
[Link]("Factorial of 4 is " + [Link](4));
}
}

Mrs. Swathi C S, Asst professor, SVIT, P a g e 20 | 29


Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

The output from this program is shown here:


Factorial of 3 is 6
Factorial of 4 is 24

• 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 methods could be said to “telescope” out and back.
• 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.
• Many recursive calls to a method could cause a stack overrun. Because storage for
parameters and local variables is on the stack and each new call creates a new copy of
these variables, it is possible that the stack could be exhausted. If this occurs, the Java
run-time system will cause an exception.
• The main advantage to recursive methods is that they can be used to create clearer and
simpler versions of several algorithms than can their iterative relatives.
• Here is one more example of recursion. The recursive method printArray( ) prints the
first i elements in the array values.

// 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);
[Link]("[" + (i-1) + "] " + values[i-1]);
}
}
class Recursion2 {
public static void main(String args[]) {
RecTest ob = new RecTest(5);
int i;
for(i=0; i<5; i++) [Link][i] = i;
[Link](5);
}
}
This program generates the following output:
[0] 0
[1] 1
[2] 2
Mrs. Swathi C S, Asst professor, SVIT, P a g e 21 | 29
Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

[3] 3
[4] 4
[5] 5

Introducing Access Control

• 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. For example, allowing access to data only
through a well-defined set of methods, you can prevent the misuse of that data.
• Thus, when correctly implemented, a class creates a “black box” which may be used, but
the inner workings of which are not open.
• Java’s access specifiers are public, private, and protected, default access level.
• An access modifier precedes the rest of a member’s type specification. That is, it must
begin a member’s declaration statement. Here is an example:
public int i;
private double j;

private int myMethod(int a, char b) { // ...

1. Public:
➢ When a member of a class is modified by public, then that member can be accessed by
any other code.
➢ The code is accessible for all classes.
➢ 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.
2. Private:
➢ When a member of a class is specified as private, then that member can only be
accessed by other members of its class.
➢ There will be times when you will want to define methods that are private to a class.
➢ The code is only accessible within the declared class.
➢ For example:
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;
Mrs. Swathi C S, Asst professor, SVIT, P a g e 22 | 29
Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

}
}
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
[Link](100); // OK
[Link]("a, b, and c: " + ob.a + " " + ob.b + " " + [Link]());
}}
• As you can see, inside the Test class, a uses default access, which for this example is
the same as specifying public. b is explicitly specified as public.
• Member c is given private access. This means that it cannot be accessed by code
outside of its class.
• So, inside the AccessTest class, c cannot be used directly. It must be accessed through
its public methods: setc( ) and getc( ).
• If you were to remove the comment symbol from the beginning of the following line,
ob.c = 100; // Error!
3. Protected:
➢ protected applies only when inheritance is involved.
➢ The code is accessible in the same package and subclasses.
➢ For example:
Package p1;
Class A{
Protected Void display(){ //same package
[Link](“Hello”);
}
package p2;
Import p1.*;
Class B extends A{
public static void main(String args[]) {
B ob = new B();
[Link]();//in another package protected method can be accessed in subclass
}
Mrs. Swathi C S, Asst professor, SVIT, P a g e 23 | 29
Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

}
4. Default:
➢ When no access modifier is specified for a class, method, or data member, It is said to
be having the default access modifier by default.
➢ The code is only accessible in the same package. This is used when you don't specify
a modifier.

Package p1;
Class Demo{
Void display(){
[Link](“Hello”);
}

package p2;
Import p1.*;
Class demodefault{
public static void main(String args[]) {
Demo ob = new Demo();
[Link]();//error because display cannot accessed outside of package.
}
}
Understanding static

•There will be times when user 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. user 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.
• 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 following example shows a class that has a static method, some static variables,
and a static initialization block:
class UseStatic {
Mrs. Swathi C S, Asst professor, SVIT, P a g e 24 | 29
Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

static int a = 3;
static int b;
static void meth(int x) {
[Link]("x = " + x);
[Link]("a = " + a);
[Link]("b = " + b);
}
static {
[Link]("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
• As soon as the UseStatic class is loaded, all of the static statements are run. First, a is
set to 3, 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.
• The three println( ) statements refer to the two static variables a and b, as well as to the
local variable x.
• Here is the output of the program:
Static block initialized.
x = 42
a=3
b = 12
• Outside of the class in which they are defined, static methods and variables can be
used independently of any object.
• To do so, only specify the name of their class followed by the dot operator.
• For example, if you wish to call a static method from outside its class, you can do so
using the following general form:
[Link]( )
• Here, classname is the name of the class in which the static method is declared.
• A static variable can be accessed in the same way by use of the dot operator on the
name of the class. This is how Java implements a controlled version of global methods
and global variables.
• Here is an example: Inside main( ), the static method callme( ) and the static variable
b are accessed through their class name StaticDemo.
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
[Link]("a = " + a);
}
}
class StaticByName {
Mrs. Swathi C S, Asst professor, SVIT, P a g e 25 | 29
Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

public static void main(String args[]) {


[Link]();
[Link]("b = " + StaticDemo.b);
}
}
Here is the output of this program:
a = 42
b = 99

Introducing final
• 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.
• 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.
• For Example:
public class Main {
final int x = 10;
public static void main(String[ ] args) {
Main ob = new Main();
ob.x = 25; // will generate an error because final var value cant be changed
[Link](ob.x);
}
}

Introducing Nested and Inner Classes

• 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
Mrs. Swathi C S, Asst professor, SVIT, P a g e 26 | 29
Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

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.
• 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 non-static members of its enclosing class through an object. That is, it
cannot refer to non-static members of its enclosing class directly.
• The second 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.
• The following program illustrates how to define and use an inner class. The class named
Outer has one instance variable named outer_x, one instance method named test( ), and
defines one inner class called Inner.

// Demonstrate an inner class.


class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
[Link]();
}

// this is an inner class


class Inner {
void display() {
[Link]("display: outer_x = " + outer_x);
}
}
}
class InnerClassDemo {
public static void main(String[] args) {
Outer outer = new Outer();
[Link]();
}
}
Output from this application is shown here:
display: outer_x = 100

• In the program, an inner class named Inner is defined within the scope of class
[Link], any code in class Inner can directly access the variable outer_x.
• An instance method named display( ) is defined inside Inner. This method displays
Mrs. Swathi C S, Asst professor, SVIT, P a g e 27 | 29
Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

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 in the context of
class Outer. The Java compiler generates an error message otherwise.
• In general, an inner class instance is often created by code within its enclosing scope, as
the example does.
• As explained, 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.
• For example,
// This program will not compile.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
[Link]();
}
// this is an inner class
class Inner {
int y = 10; // y is local to Inner
void display() {
[Link]("display: outer_x = " + outer_x);
}
}
void showy() {
[Link](y); // error, y not known here!
}
}
class InnerClassDemo {
public static void main(String[] args) {
Outer outer = new Outer();
[Link]();
}
}
• 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 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:
// Define an inner class within a for loop.
class Outer {
int outer_x = 100;
void test() {
Mrs. Swathi C S, Asst professor, SVIT, P a g e 28 | 29
Bengaluru
Object Oriented Programming with JAVA(BCS306A) Module-2

for(int i=0; i<5; i++) {


class Inner {
void display() {
[Link]("display: outer_x = " + outer_x);
}
}
Inner inner = new Inner();
[Link]( );
}
}}
class InnerClassDemo {
public static void main(String[ ] args)
{
Outer outer = new Outer();
[Link]();
}
}
The output from this version of the program is shown here:
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100
display: outer_x = 100

• While nested classes are not applicable to all situations, they are particularly helpful
when handling events.

Mrs. Swathi C S, Asst professor, SVIT, P a g e 29 | 29


Bengaluru

You might also like