Java Module 2
Java Module 2
MODULE II
MODULE II
Contents
Introducing Classes.
Class Fundamentals.
Demonstration of a Class Creation & assigning Objects Reference Variable
Assigning Object Reference Variables
Introducing Methods
Constructors
this Keyword
Garbage Collection
Methods and Classes
Overloading Methods
Objects as Parameters, Argument Passing, Returning Objects
Recursion
Access Control
Understanding static, Introducing the final keyword
Introducing Nested and Inner Classes.
Introducing Classes
Class Fundamentals
Class 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.
Because an object is an instance of a class, you will often see the two words object
and instance used interchangeably.
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.
1
Object-Oriented Programming with JAVA: BCS306A
MODULE II
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 copy of these variables.
Thus, the data for one object is separate and unique from the data for another.
Syntax:
Class classname{
type instance variable1;
type instance variable2;
……….
type methodname(parameter – list){
//body of method
}
type mathodname(parameter – list){
//body of method
}
}
Here is a class called Box that defines three instance variables: width, height, and
depth.
class Box{
double width;
double height;
double depth;}
As stated, a class defines a new type of data.
In this case, the new data type is called Box.
You will use this name to declare objects of type Box.
It is important to remember that 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 Box.
Thus, it will have a “physical” reality.
2
Object-Oriented Programming with JAVA: BCS306A
MODULE II
Thus, every Box object will contain its 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;
3
Object-Oriented Programming with JAVA: BCS306A
MODULE II
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
This statement combines the two steps just described. It can be rewritten like this to
show each step more clearly: Box mybox; // declare reference to object mybox = new
Box(); // allocate a Box object
The first line declares mybox as a reference to an object of type Box.
After this line executes, mybox contains the value null, which indicates that it does
not yet point to an actual object.
Any attempt to use mybox at this point will result in a compile-time error. 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.
Introducing methods
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.
4
Object-Oriented Programming with JAVA: BCS306A
MODULE II
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.
5
Object-Oriented Programming with JAVA: BCS306A
MODULE II
That is, it calls volume () relative to the Box1 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,
There is something very important to notice 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 the use of the dot operator.
This is easy to understand if you think about it. A method is always invoked relative
to some object of its class. Once this invocation has occurred, the object is known.
}
public static void main(String[] args) {
Box Box1= new Box(); //creating an object in the class
Box Box2= new Box ();
[Link]=3;
[Link]=3;
[Link]=3;
[Link]=2;
[Link]=4;
[Link]=5;
[Link]("The volume of first box is " +
[Link]());
[Link]("The volume of second box is "
+[Link]());
}
A Closer Look at the Program
int volume(), to name a method with a return type answer the structure is
data type methodname().
There are two important things to understand about returning values:
6
Object-Oriented Programming with JAVA: BCS306A
MODULE II
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 cannot 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
several slightly different situations.
Demonstration of Class Creation by Adding a Method that takes Parameters
public class Box {
int length;
int breadth;
int width;
int volume() {
return (length* width*breadth);
}
//In the beneath line we have to use void since there is no
return answer in the method
void SetDim(int l, int b,int h) {
length=l;
breadth=b;
width = h;
}
public static void main(String[] args) {
Box Box1=new Box ();
Box Box2=new Box();
[Link](3,4,6);
[Link](12,14,16);
[Link]("The volume of First Box is "+
[Link]());
[Link]("The volume of Second Box is "+
[Link]());
}
}
Output: The volume of the First Box is 72
The volume of the Second Box is 2688
7
Object-Oriented Programming with JAVA: BCS306A
MODULE II
Constructors
In Java, constructors can be divided into 3 types:
No-Arg Constructor.
Parameterized Constructor.
Default Constructor.
Let us understand the term Constructors
It is called a constructor because it constructs the values at the time of object creation.
It can be tedious to initialize all of the variables in a class each time an instance is
created.
Even when you add convenience functions like setDim( ), it would be simpler and
more concise to have all of the setup done at the time the object is first 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 look a little strange because they have no return type, not even void.
This is because the implicit return type of a class’s 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.
8
Object-Oriented Programming with JAVA: BCS306A
MODULE II
No-Arg Constructor
The default constructor is as its name, if we do not create a constructor explicitly then
the Java compiler will create a default constructor. As a developer, if we create our
constructor with 0 arguments then it will be no argument constructor.
Parameterized Constructor
As the name suggests parametrized constructor in Java is a type of constructor that
takes one or more parameters as arguments. It is used to initialize the object with the values
passed by the user as the arguments while declaring the object.
Default constructor
The default constructor in Java is created by the compiler itself when the programmer
doesn't create any constructor. The purpose of the default constructor is to initialize the
attributes of the object with their default values.
9
Object-Oriented Programming with JAVA: BCS306A
MODULE II
10
Object-Oriented Programming with JAVA: BCS306A
MODULE II
// constructors
ThisKeyWord(){ // default
constructor.
}
ThisKeyWord(int speed){
// takes only one arg.
[Link] = speed;
}
ThisKeyWord(int weight, int speed) {
// takes two args.
[Link] = weight;
[Link] = speed;
}
[Link]([Link]);
[Link]([Link]);
}
}
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’s instance variables.
However, when a local variable has the same name as an instance variable, the local
variable hides the instance variable.
We can use this keyword to resolve name–space collisions
11
Object-Oriented Programming with JAVA: BCS306A
MODULE II
Garbage Collection
Since objects are dynamically allocated by using the new operator, you might be
wondering how such objects are destroyed and their memory released for later
reallocation.
Java takes a different approach; it handles deallocation for you automatically.
The technique that accomplishes this is called garbage collection.
It works like this: when no references to an object exist, that object is assumed to be
no longer needed, and the memory occupied by the object can be reclaimed.
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.
A Stack Class
A stack is a linear data structure in which the insertion of a new element and
removal of an existing element takes place at the same end represented as the top of the
stack. To implement the stack, it is required to maintain the pointer to the top of the stack,
which is the last element to be inserted because we can access the elements only on the top
of the stack. Stack work with the LIFO principle.
LIFO (Last in First Out):
This strategy states that the element that is inserted last will come out first. You can
take a pile of plates kept on top of each other as a real-life example. The plate which we put
last is on the top and since we remove the plate that is at the top, we can say that the plate
that was put last comes out first. The stack can be considered as an example of
encapsulation.
Demonstration of Creation of A Stack class with numbers 1 to 10
import [Link];
[Link]([Link]());
12
Object-Oriented Programming with JAVA: BCS306A
MODULE II
}
}
OutPut:
9
8
7
6
5
4
3
2
1
0
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.
13
Object-Oriented Programming with JAVA: BCS306A
MODULE II
Overloading Constructors
14
Object-Oriented Programming with JAVA: BCS306A
MODULE II
int breadth;
//In the below codes constructors are used when all
dimensions are specified
Box(int l, int w, int b){
length=l;
width=w;
breadth=b;
}
//constructors used when no dimensions are specified
Box(){
length=2;
width=3;
breadth=7;
}
//constructors used to calculate for a cube
Box(int l){
length=width=breadth=l;
}
int volume() {
return (length*width*breadth);
}
}
Using Object as Parameters
When you pass an object to a method, the situation changes dramatically, 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. 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.
15
Object-Oriented Programming with JAVA: BCS306A
MODULE II
}
int volume() {
return width*height*depth;
}
}
public class OverloadDemo {
16
Object-Oriented Programming with JAVA: BCS306A
MODULE II
}
A closer Look at the program
First, we have constructed a class called Box
In that we have demonstrated how we will pass the values through the constructor as
in the previous program.
Using the code Box(Box obj) we are passing the values through the object of that
class
Next, we have constructed a new class called OverloadDemo to test whether all the
overloading method works.
To pass the values through the object we have created a copy of the object using the
code Box copy= new Box(mybox1) and passed this new object copy through the
constructor using the code Box mybox3= new Box(mybox1).
Returning Objects
A method can return any type of data, including class types you create. For example,
in the following program, the increByten() method returns an object in which the value of a is
ten greater than it is in the invoking object.
public class Test {
int a;
Test(int i){
a=i;
}
Test incr() {
Test obj= new Test(a+10);
return obj;
}
public static void main(String[] args) {
Test obj1=new Test(2);
Test obj2;
obj2=[Link]();
17
Object-Oriented Programming with JAVA: BCS306A
MODULE II
[Link](obj1.a);
[Link](obj2.a);
}
}
A closer look at the program
Each time increByten() is invoked, a new object is created. And a reference to it is
returned to the calling function.
Since all the objects are dynamically allocated using new, you don’t need to worry
about an object is going out of scope, because the method in which it was created
terminates. The object will continue to exist as long as there is a reference to it, the
object will be reclaimed the next time garbage collection takes place.
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:
int result;
int cal(int n) {
if (n==1) return 1;
result=cal(n-1)*n;
return result;
}
public static void main(String[] args) {
Factorial object1= new Factorial();
[Link]([Link](3));
[Link]([Link](6));
}
}
A Closer Look at the Program
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.
18
Object-Oriented Programming with JAVA: BCS306A
MODULE II
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.
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.
Protected Access Modifier - This modifier can be applied to the data member,
method, and constructor, but this modifier can’t be applied to the top-level classes and
interface. A member is declared as protected as we can access that member within the
current package and only in the child class of the outside package.
The scope of a nested inner class is bounded by the scope of its enclosing class.
Thus, if class B is defined within class A, then B does not exists independently of A.
A nested class has access to the members, including private members, of a class in
which it is nested.
However, the enclosing class does not have access to the members of the nested class.
19
Object-Oriented Programming with JAVA: BCS306A
MODULE II
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.
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. Because of this restriction, static nested classes are
seldom used.
20
Object-Oriented Programming with JAVA: BCS306A
MODULE II
Nested classes represent a particular type of relationship that is it can access all the
members (data members and methods) of the outer class, including private.
Nested classes are used to develop more readable and maintainable code because it
logically groups classes and interfaces in one place only.
Code Optimization: It requires less code to write.
Sometimes users need to program a class in such a way that no other class can access
it. Therefore, it would be better if you included it in other classes. If all the class objects are a
part of the outer object, then it is easier to nest that class inside the outer class. That way all
the outer class can access all the objects of the inner class.
Here all the classes are above the main methods. So, it will come under the category
of Member Inner Class. Demonstrating that all inner classes can access all outer class data
and objects. Also, a Private variable can be accessed by the inner class created by an outer
class and defined as a private variable as data.
class OuterClass {
}
}
21
Object-Oriented Programming with JAVA: BCS306A
MODULE II
22