2 - Classes, Objects - Methods
2 - Classes, Objects - Methods
Learning Objectives:
● Classes
● Objects: Declaring and assignment
● Methods
● Using Parameters
● Constructors
● ‘this’ Keyword
● Scanner Class
● Garbage Collection
● Overloading: Methods and Constructors
● Objects as parameters
● Recursion
● Access Control
● Static and Final Keyword
● Nested and Inner Classes
● Command Line Arguments, Varargs
Classes
A class is used to create a new datatype. Classes may contain only code or only data or
both. A class can be declared by using the keyword ‘class’. The general form of a class definition
is as shown below,
1
class class_name{
datatype instance_variable1;
datatype instance_variable2;
datatype instance_variableN;
returntype method_name1(arg-list){
//Body
}
returntype method_name2(arg-list){
//Body
}
returntype method_nameN(arg-list){
//Body
}
}
The variables created inside a class are called as instance variables. The code contained
within the class is called as methods. Collectively they are called as members of a class.
2
Object Declaration
Creating a class is equivalent to creating a datatype. Using this datatype, new objects can
be declared. The process of creating objects of a class is called “creating instances of a class”.
1. To declare a variable of a class type. This variable does not represent an object. It is only
a reference to an object.
2. Actual physical copy of an object must be obtained by using the new operator and it must
be assigned to the variable.
3
Consider the following example,
The effect of the above given code can be pictorially represented as shown below,
Statement Effect
Stack ob;
ob
s[0]
s[1]
s[2]
s[3]
s[4]
s[5]
s[6]
s[7]
s[8]
s[9]
ob = new Stack( );
ob
Stack ob1;
Stack ob2;
ob1 = new Stack( );
ob2 = ob1;
4
Methods
A method is a way to perform some task. The method in Java is a group of instructions that
performs a specific task. We can also easily modify code using methods. The most important
method in Java is the main() method. The declaration of methods is as shown below,
Access specifier can be from public, private, protected, default. Type of the method can any valid
primitive type, object, collections or void. Name of the method follows the rule of valid identifier
and parameter list may be passed based on the method requirement.
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.
Consider the following example which defines a method with parameters and returns a value to
the main method.
5
Output:
Value of a = 29
Constructors
A constructor is used to immediately initialize an object upon creation. It has the same name as
that of the class. A constructor would have a syntax very similar to a method.
Normally, it is a tedious job to initialize all the variables in a class each time an object is created.
Since the requirement is so common that a constructor must be used. A constructor is called
immediately after the object is created. It has no return type. In fact the implicit return type of a
constructor is the class type itself.
When the programmer does not explicitly define a constructor, then Java creates a default
constructor for the class.
6
Parameterized Constructors
A Constructor can also be passed with parameters to initialize the instance variables. Consider
the following program,
7
The this Keyword – Instance variable Hiding
In Java, it is legal to have the local variable i.e., formal parameter name same as that of instance
variable. However, the local variable hides the instance variable, when the name of local and
instance variable are given the same names.
The problem of hiding instance variable can be rectified using ‘this’ keyword. Using ‘this’ refers
to the instance variable rather than the local variable name.
8
Garbage Collection
Objects in java are dynamically allocated by using the new operator. Java takes a different
approach to deallocate this memory, it handles deallocation automatically. The technique which
makes this automatic deallocation is called garbage collection.
Its working is simple: when there are no references to an object, then that object is assumed to
be no longer required, and the memory occupied by the object can be reclaimed. 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.
Before an object is being destroyed, there may be a situation where an object has to perform
some action. For example, if an object is holding some resource such as a file handle etc, then
you might want to make sure these resources are freed before an object is destroyed. To handle
such situations, 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.
To add a finalizer to a class, simply define the finalize( ) method. The Java runtime calls this
method whenever it is about to recycle an object of that class. Inside the finalize( ) method you
will specify the actions that must be performed before an object is destroyed. The garbage
collector runs periodically, checking for objects that are no longer referenced by any running
state or indirectly through other referenced objects. Right before an asset is freed, the Java
runtime calls the finalize( ) method on the object. The finalize( ) method has this general form:
9
protected void finalize( )
{
// Code that need to be executed before garbage collection
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
Scanner Class
Java supports various classes to read characters from the keyboard, one such simple and most
widely used class for this is Scanner, which is present in the package java.util.
The Scanner class provides methods to read integer, float, string, character etc.
Method Description
nextInt() Reads an integer
nextLine() Reads a string until new line
character
next() Reads a string until space
nextFloat() Reads an floating point value
nextChar() Reads a character value
Method overloading refers to the process of two or more methods having the same name with
different signatures. Method overloading is the way of implementing polymorphism.
When an overloaded method is invoked java uses the signature to determine which version of the
overloaded method to actually call. The signature may be different in
10
1. Number of parameter
2. Type of Parameter
3. Order of parameter
11
Using Objects as Parameters
Apart from using simple types as parameters to methods, it is both correct and common to pass
objects to methods. For example, consider the following short program,
Output:
ob1 == ob2: true
ob1 == ob3: false
12
Returning Objects
A method can return any type of data, which may include class types or any other type. 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.
Output:
ob1.a: 2
ob2.a: 12
ob2.a after second increase: 22
It can be noticed form the above program that a new object is created, and a reference to it is
returned to the calling routine when incrByTen( ) is invoked each time.
Recursion
Java supports recursion. Recursion is the process of defining something in terms of itself. A
method that calls itself is said to be a recursive method.
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, 5 factorial is
1 × 2 × 3 × 4 × 5, or 120. Here is how a factorial can be computed by use of a recursive method:
13
Output:
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Access control is a mechanism, which restricts the access of certain members of a class to
specific parts of a program. Access to members of a class can be controlled using the access
modifiers. There are four access modifiers in Java. They are:
1. public
2. protected
3. default
4. private
If the member (variable or method) is not marked as either public or protected or private, the
access modifier for that member will be default. We can apply access modifiers to classes also.
Among the four access modifiers, private is the most restrictive access modifier and public is the
least restrictive access modifier. Syntax for declaring a access modifier is shown below:
Syntax: access-modifier data-type variable-name;
Packages and inheritance will have effect on access-modifiers. Accessibility restrictions of the
four access modifiers is as shown below,
14
Within Within Within Within
Access Subclass Non-Subclass Subclass Non-Subclass
Within Class
Modifiers Same Same Different Different
Package Package Package Package
public Yes Yes Yes Yes Yes
private Yes No No No No
protected Yes Yes Yes Yes No
default Yes Yes Yes No No
Understanding ‘static’
The ‘static’ keyword can be applied to either method or a variable in Java. Any member
declared as a static member will be class member rather than an instance member. ‘static’
members are like global members for each object created for a class.
‘static members are not invoked using the object of a class, rather they are invoked using
the name of the class in which the static members are declared.
It is also possible to declare a static block in order to initialize static variables in Java.
15
Output:
Static Block Initialized
X = 42
A=3
B = 12
Final Keyword
Class A{
final int a = 100;
/* The below statement is illegal since ‘a’ is constant, modifying constant value is
not allowed */
// a = a + 20;
16
}
Java Supports to define a class within another class, such a class is known as nested
classes. The scope of a nested class is bounded by the scope of its enclosing class.
There are two types of nested classes: static and non-static. A static nested class is one
that has the static modifier applied. The most important type of nested class is the inner class. An
inner class is a non-static nested class. An inner class would have access to all the variables and
methods of an outer class.
Consider an example,
17
As mentioned in the above example, the inner class ‘Inner’ can access the variable outer_x,
which belongs to the outer class.
However, it is important to note that instance if Inner can be created only within the
scope of the class Outer. Moreover, the inner class can access all the members of the outer class
but the vice-versa is not true.
Command-Line Arguments
Sometimes to pass the information into a program that is running, command line
arguments to main( ) can be used.
Output:
18
java CommandLine this is a test 100 -1
args[0] : this
args[1] : is
args[2] : a
args[3] : test
args[4] : 100
args[5] : -1
With JDK 5, Java included a feature to take variable number of arguments. This feature is
called ‘varargs’(variable-length arguments). A method that takes a variable number of arguments
is called a variable-arity method or varargs method.
Output:
Number of args: 1 Contents: 10
Number of args: 3 Contents: 1 2 3
Number of args: 0 Contents:
A method can have normal parameters along with a variable-length parameter. However,
variable length parameter must be the last parameter declared by the method. For example,
19
void vaTest(int a, int b, double c, int … var)
But following declarations will produce an ERROR, since the varargs parameters are not
specified as the last last argument and even a method can have only one varargs parameters, it
cannot have more than one varargs parameter. For example,
20