Java Module2ISE
Java Module2ISE
MODULE 2
Introducing Classes:
Class Fundamentals
Declaring Objects
Assigning Object Reference Variables
CLASSES Introducing Methods
Constructors
The this Keyword
METHODS 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 -1
Introducing Classes
Class Fundamentals:
Qp) Write a note on
a. defining class in java
b. object instantiation
The data, or variables, defined within a class are called instance variables.
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.
All methods have the same general form as main( ), which we have been using thus
far. However, most methods will not be specified as static or public.
Note: The general form of a class does not specify a main( ) method. Java classes do
not need to have a main( ) method. You only specify one if that class is the starting
point for your program. Further, applets don’t require a main( ) method at all.
Example:
package mypack;
public class box
{
double width;
double height;//creates only a template
double depth;//no actual data
}
class boxdemo1
{
public static void main(String[] args)
{
box mybox=new box();//create a box object called mybox
double vol;
mybox.width=10;
mybox.height=10;
mybox. depth=15;
vol=mybox.width*mybox.height*mybox. depth;
System.out.println("volume is "+vol);
}
package mypack;
public class box
{
double width;
double height;//creates only a template
double depth;//no actual data
}
class boxdemo1
{
public static void main(String[] args)
{
box mybox1=new box();//create a box object called mybox1
box mybox2=new box();// 2nd object called mybox2
double vol;
mybox1.width=10; Output:
mybox1.height=20; Volume is 3000.0
mybox1. depth=15; Volume is 162.0
mybox2.width=3;
mybox2.height=6;
mybox2. depth=9;
Declaring object:
b. Object Instantiation
Object is a instance of the class.
Object is used to access members and member functions.
When you create a class, you are creating a new data type. You can use this type to
declare objects of that type.
Object is created using new keyword , which allocates the memory for object when its
created.
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 then stored in the variable.
This statement combines the two steps just described. It can be rewritten like this to
show each step more clearly:
mybox NULL
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.
mybox width
height
depth
Box object
The above line allocates an actual object and assigns a reference to it to mybox. After
the second line executes, you can use mybox as a Box object.
But in reality, mybox simply holds the memory address of the actual Box object.
Assigning object Reference Variables:
A reference variable is used to access the object of a class. Reference variables are created at the
program compilation time.
Reference variable is just a alias name for object.
Object reference variables act differently than you might expect when an assignment takes place.
width
Height
For example, b1
Box b1=new Box( ) ; Depth
Box b2=b1 ; b2
Box object
We might think that b2 is being assigned a reference to a copy of the object referred to by
b1. That is, we might think that b1and b2 refer to separate and distinct objects.
However, this would be wrong. Instead, after this fragment executes, b1and 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 b1is
referring, since they are the same object.
Example:b1=null;
b1 will simply unhook b1 from the original object without affecting the object b2.
b1 has been set to null, but b2 still points to the original object.
Introducing Methods:
We already know that class contains members (instance variables) and member functions
(methods).
This is the general form of a method:
<Access modifier><Return type><Method name>(parameter List)
{
// Method body
Access modifier: this determines the visibility of a variable or a method from another class.
Return type: A method may return a value. If a method is not returning any value then method return
data type should be void, if method returning integer value then method return type should be int, etc.,
Method name: It’s a unique identifier and it’s case sensitive. It cannot be same as any other identifier.
Parameter List: enclosed between parenthesis. Parameter List is optional that is, a method may contain
no parameters.
Method Body: this contains the set of instructions need to complete the required activity.
Scope
Local Scope:
o The variables which are declared inside one method, we cannot use the same
variables in other method.
o The left and right curly braces that form the body of a method create scope.
Class Scope:
o The variable which are declared inside the class and outside all the methods,
which are used in any methods known as Class Scope.
package mypack;
package mypack;
Definition: it is method which is having same name as that of the class in which it is
defined.
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’ 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.
Every time an object is created using the new( ) keyword, at least one constructor is
called.
It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default.
Two types of constructors are
a. Default constructor
b. Parameterized constructor
a) Default constructor:
If a constructor method doesn’t have any parameters then we call it as parameter less
constructor or default constructor.
These methods can be defined by the programmer explicitly, or else will be defined
implicitly provided by the compiler.
In Implicit constructors, the default value for integer is 0, for boolean is false, for string is null.,
etc.
class Box
{
double width;
double height;
double depth;
OUTPUT:
Box()
{ Volume is 1000.0
width = 10; Volume is 1000.0
height = 10;
depth = 10;
}
double volume()
{
return width * height * depth;
}
}
class BoxDemo {
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
b) Parameterized Constructors
If a Constructor method is defined with parameters, we call that as parameterized
constructor.
Parameterized constructor should be defined by the programmer but never defined by the compiler
implicitly.
class Box
{
double width;
double height;
double depth;
class BoxDemo
{
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
this keyword:
In Java, this is a reference variable that refers to the current object.
Uses –
this can be used to refer current class instance variable.
this can be used to invoke current class method (implicitly)
this( ) can be used to invoke current class constructor. Etc..,
The this keyword can be used to refer current class instance variable. If there is ambiguity
(confusion) between the instance variables and local parameters, this keyword resolves the problem
of ambiguity.
this.width = width;
this.height = height;
this.depth = depth;
}
Qp)Write a note on
c. instance variable hiding(use of this keyword)
d. static and static block
e. garbage collection
f. finalization(finalize())
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:
The use of this in such a context can sometimes be confusing, and some programmers
are careful not to use local variables and formal parameter names that hide instance
variables.
S
ttatic
{
System.out.println("Static block initialized.");
b = a * 4;
}
output :
Static block initialized.
x = 42
a=3
b = 12
If you wish to call a static method from outside its class, you can do so using the
following general form:
classname.method( )
Here, classname is the name of the class in which the static method is declared
Example:
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();//no object is needed for static
System.out.println("b = " + StaticDemo.b);
}
}
output
a = 42
b = 99
c. 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.
In some languages, such as C++, dynamically allocated objects must be manually
DEPT OF ISE,SJCIT 2023 Page 14
MODULE 2 CLASSES and METHODS
released by use of a delete operator. Java takes a different approach; it handles ideal
location 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.
Furthermore, different Java run-time implementations will take varying approaches to
garbage collection.
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
It is important to understand that finalize( ) is only called just prior to garbage
collection. It is not called when an object goes out-of-scope, for example. This means
Qp)Write a JAVA program to implement the stack operations that holds 10 elements?
// Initialize top-of-stack
Stack()
{
top= -1;
}
Class StackDemo
{
Public static void main(String args[])
{
Stack ob=new stack(10);
for(int i=0;i<10;i++)
ob.push(i);
System.out println(“elements of stack are”);
for(int i=0;i<10;i++)
ob.pop();
}
}
As you can see, the Stack class defines two data items and three methods. The stack
of integers is held by the array stck. This array is indexed by the variable top, which always
contains the index of the top of the stack.
The Stack( ) constructor initializes top to –1, which indicates an empty stack. The
method push( ) puts an item on the stack. To retrieve an item, call pop( ). Since access to the
stack is through push( ) and pop( ), the fact that the stack is held in an array is actually not
relevant to using the stack.
output:
Stack elements are:
9
8
7
6
5
4
3
2
1
0
Chapter -2
Methods and classes
Method overloading:
Java allows us to create more than one method with same name, but with different
parameter list and different definitions. This is called method overloading.
Method overloading is used when methods are required to perform similar tasks but using
different input parameters. Overloaded methods must differ in number and/or type of
parameters they take. This enables the compiler to decide which one of the definitions to
execute depending on the type and number of arguments in the method call.
Example:
public class First
{
public void Addition( int a, int b)
{
System.out.println(a+b);
}
public void Addition( int a, int b,int c) Output:
{ 30
System.out.println(a+b+c); 60
}
public static void main(String[] args){
First obj = new First( ) ;
obj.Addition(10, 20);
obj.Addition(10, 20, 30);
}}
Objects and methods (Using Objects as Parameters to methods):So far, we have only been using simple
types as parameters to methods. However, it is bothcorrect and common to pass objects to methods
public class test
int a,b;
test(int i,int j)//parameterized constructor
a=i;b=j;
1. Call-by-value
2. Call-by-reference.
Pass/call-by-Value:
When a parameter is pass-by-value, the caller and the callee method operate on two different variables
which are copies of each other. Any changes to one variable don’t modify the other.
It means that while calling a method, parameters passed to the callee method will be clones of
original parameters. Any modification done in callee method will have no effect on the original
parameters in caller method.
public class test
{
void meth(int i,int j)
{
i*=2; Output:
j/=2; a and b before call:15 20
} a and b after call:15 20
}
class callbyvalue
{
public static void main(String[] args)
{
test ob=new test();
int a=15,b=20;
Pass/call-by-Reference:
When a parameter is pass-by-reference, the caller and the callee operate on the same object.
It means that when a variable is pass-by-reference, the unique identifier of the object is sent to the
method. Any changes to the parameter’s instance members will result in that change being made to the
original value.
class test1
{
int a,b;
test1(int i,int j)//constructor
{
a=i;
b=j;
}
void meth(test1 o)//object as the parameter
Output:
{ value. Output:
original
o.a *=2; ob.a and ob.b before call:15 20
o.b /=2; ob.a and ob.b after call: 30 10
}
}
public class CallByRef
{
System.out.println("ob.a and ob.b after call: " +ob.a +" " +ob.b);
}
}
Returning object:
A method can return any type of data ,including class types that you create.
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.
class test
{
int a;
test (int i)
{
a=i;
}
test incrbyten()
{
test temp=new test(a+10);
return temp; Output:
} Ob1.a :2
} Ob2.a :12
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 );
}
}
Recursion:
Recursion is the process of defining something in terms of itself.
DEPT OF ISE,SJCIT 2023 Page 20
MODULE 2 CLASSES and METHODS
Types:
Default
Public
Private
Protected
Public Y Y Y Y
Private Y N N N
Protected Y Y Y N
Public:
The access level of a public modifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.
It has the widest scope among all other modifiers.
Private :
The access level of a private modifier is only within the class. It cannot be accessed from outside
the class.
Protected:
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It
can't be applied on the class.
Default:
The access level of a default modifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.
class test
{
int a;//default access
public int b;//public access
Default:
private int c;// private access
void setc(int i)
Default:
{
c=i;
}
int getc()
{
return c;
}
}
class accesstest
{
public static void main(String args[])
{
test ob=new test();
//a and b can access directly
ob.a=10;
ob.b=20;
ob.c=100;//error
//you must access c through its method
ob.setc(100);;
System.out.println("a,b,and c:"+ob.a +"" + ob.b + "" + ob.getc());
DEPT OF ISE,SJCIT 2023 Page 22
}
}
MODULE 2 CLASSES and METHODS