Object Oriented Programming with JAVA(BCS306A) Module 2
Module 2
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.
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. As such, the class forms the basis for object-
oriented programming in Java.
Class Fundamentals
Perhaps the most important thing to understand about 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. Because an object is an instance of a class, you will
often see the two words object and instance used interchangeably.
.IN
The General Form of a Class
A class is declared by use of the class keyword.
C
A simplified general form of a class definition is shown here:
N
SY
U
VT
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.
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 1
Object Oriented Programming with JAVA(BCS306A) Module 2
.IN
You should call the file that contains this program BoxDemo.java, because the main( ) method is in
C
the class called BoxDemo, not the class called Box. When you compile this program, you will find
that two .class files have been created, one for Box and one for BoxDemo. The Java compiler
N
automatically puts each class into its own .class file. It is not necessary for both the Box and the
BoxDemo class to actually be in the same source file. You could put each class in its own file, called
SY
Box.java and BoxDemo.java, respectively. To run this program, you must execute BoxDemo.class.
When you do, you will see the following output:
Volume is 3000.0
U
Declaring Objects
VT
When you create a class, you are creating a new data type. You can use this type to declare objects of
that 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.
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 2
Object Oriented Programming with JAVA(BCS306A) Module 2
A Closer Look at new
As just explained, the new operator dynamically allocates memory for an object. It has this general
form:
class-var = new classname ( );
.IN
C
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
N
class. A constructor defines what occurs when an object of a class is created.
Introducing Methods
SY
classes usually consist of two things: instance variables and methods.
This is the general form of a method:
U
type name(parameter-list)
{
VT
// 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
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 3
Object Oriented Programming with JAVA(BCS306A) Module 2
Adding a Method to the Box Class
.IN
C
N
SY
U
VT
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 4
Object Oriented Programming with JAVA(BCS306A) Module 2
Returning a Value
.IN
C
N
SY
U
There are two important things to understand about returning values:
VT
• 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.
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 5
Object Oriented Programming with JAVA(BCS306A) Module 2
Constructors
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 when the object is created, before the new operator completes.
.IN
C
N
SY
U
VT
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 6
Object Oriented Programming with JAVA(BCS306A) Module 2
Parameterized Constructors
While the Box( ) constructor in the preceding example does initialize a Box object, it is not very
useful—all boxes have the same dimensions. What is needed is a way to construct Box objects of
various dimensions. The easy solution is to add parameters to the constructor.
.IN
C
N
SY
U
VT
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 7
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. To better understand what this refers to, consider the
following version of Box( ):
Garbage Collection
Java handles deallocation for you automatically. The technique that accomplishes this is called
.IN
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.
The finalize( ) Method
C
if an object is holding some non-Java resource such as a file handle or character font, then you might
want to make sure these resources are freed before an object is destroyed. To handle such situations,
N
Java provides a mechanism called finalization. By using finalization, you can define specific actions
that will occur when an object is just about to be reclaimed by the garbage collector.
SY
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. Inside the finalize( ) method, you will
specify those actions that must be performed before an object is destroyed.
U
VT
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.
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 8
Object Oriented Programming with JAVA(BCS306A) Module 2
.IN
C
N
SY
U
VT
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 9
Object Oriented Programming with JAVA(BCS306A) Module 2
Overloading Constructors
In addition to overloading normal methods, you can also overload constructor methods. In fact, for
most real-world classes that you create, overloaded constructors will be the norm, not the exception.
.IN
C
N
SY
U
VT
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 10
Object Oriented Programming with JAVA(BCS306A) Module 2
Using Objects as Parameters
.IN
C
N
SY
U
VT
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 11
Object Oriented Programming with JAVA(BCS306A) Module 2
.IN
Closer Look at 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
C
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
N
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
SY
changes made to the parameter will affect the argument used to call the subroutine.
U
VT
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 12
Object Oriented Programming with JAVA(BCS306A) Module 2
.IN
C
N
SY
Recursion
Java supports recursion. Recursion is the process of defining something in terms of itself. As it relates
U
to Java programming, recursion is the attribute that allows a method to call itself. A method that calls
itself is said to be recursive.
VT
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 13
Object Oriented Programming with JAVA(BCS306A) Module 2
INTRODUCING ACCESS CONTROL
How a member can be accessed is determined by the access modifier attached to its declaration. Java
supplies a rich set of access modifiers. Some aspects of access control are related mostly to
inheritance or packages. (A package is, essentially, a grouping of classes.)
Java’s access modifiers are public, private, and protected. Java also defines a default access level.
protected applies only when inheritance is involved.
When a member of a class is modified by public, then that member can be accessed by any other
code. When a member of a class is specified as private, then that member can only be accessed by
other members of its class. Now you can understand why main( ) has always been preceded by the
public modifier. It is called by code that is outside the program—that is, by the Java run-time system.
When no access modifier is used, then by default the member of a class is public within its own
package, but cannot be accessed outside of its package.
.IN
UNDERSTANDING STATIC
When a member is declared static, it can be accessed before any objects of its class are created, and
C
without reference to any object. You 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.
N
Methods declared as static have several restrictions:
SY
• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way. (The keyword super relates to inheritance and is
U
described in the next chapter.)
VT
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 14
Object Oriented Programming with JAVA(BCS306A) Module 2
INTRODUCING FINAL
A field can be declared as final. Doing so prevents its contents from being modified, making it,
essentially, a constant. This means that you must initialize a final field when it is declared. You can do
this in one of two ways: First, you can give it a value when it is declared. Second, you can assign it a
value within a constructor.
It is a common coding convention to choose all uppercase identifiers for final fields, as this example
.IN
shows. In addition to fields, both method parameters and local variables can be declared final.
Declaring a parameter final prevents it from being changed within the method. Declaring a local
variable final prevents it from being assigned a value more than once
C
Introducing Nested and Inner Classes
It is possible to define a class within another class; such classes are known as nested classes. The
N
scope of a nested class is bounded by the scope of its enclosing class. A nested class has access to the
members, including private members, of the class in which it is nested. However, the enclosing class
SY
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
U
enclosing class directly. Because of this restriction, static nested classes are seldom used. The most
important type of nested class is the inner class. An inner class is a non-static nested class. It has
VT
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.
Jayasri Sivapuram, Assistant Professor, Dept. of ISE, AJIET, Mangaluru 15