Ooptj r23 Unit 2
Ooptj r23 Unit 2
1. INTRODUCTION TO CLASS
Fundamentals of the class
A class is a group of objects that has common properties. It is a template or blueprint from
which objects are created. The objects are the instances of class. Because an object is an
instance of a class, you will often see the two words object and instance used interchangeably.
A class is used to define new type of the data. Once defined, this new type can be used to create
objects of its type. The class is the logical entity and the object is the logical and physical entity.
A Simple Class
class Box
{ //instance variables
double width;
double height;
double depth;
}
As stated, a class defines new data type. The new data type in this example is, Box. This defines
the template, but does not actually create object.
Note: By convention the First letter of every word of the class name starts with Capital letter, but
not compulsory. For example “box” is written as “Box” The First letter of the word of the
method name begins with small and remaining first letter of every word starts with Capital letter,
but not compulsory. For example “boxVolume()”
Step 1:
Box b;
Effect: b null
Declares the class variable. Here the class variable contains the value null. An attempt to access
the object at this point will lead to Compile-Time error.
Step 2:
Box b=new Box();
Here new is the keyword used to create the object. The object name is b. The new operator
allocates the memory for the object, that means for all instance variables inside the object,
memory is allocated.
Width
Effect: b Height
Depth
Box Object
Step 3:
There are many ways to initialize the object. The object contains the instance variable.
The variable can be assigned values with reference of the object.
b.width=12.34;
b.height=3.4;
b.depth=4.5;
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 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.
To run this program, you must execute BoxDemo.class.
OUTPUT:
Volume is 3000.0
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:
2. MODIFIERS
There are two types of modifiers in Java: access modifiers and non-access modifiers.
Access Modifiers
There are four types of Java access modifiers:
private
default/No Modifier
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default/No Modifier: 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.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. 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.
Access Modifier within class within package outside package by subclass only outside package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Example:
class AccessDemo
{
private Int a;
int b;
public int c;
}
class AccessDemoMain
{
public static void main(String[]args)
{
a=10; //compile time error
SACET, CSE Department, II CSE I SEM ( R23) Page 4
b=20;
c=30;
}
}
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;
Returning a Value
A method can also return the value of specified type. In this case the type of the method should
be clearly mentioned. The method after computing the task returns the value to the caller of the
method.
double volume()
{
return (width*height*depth);
}
}
class BoxDemo3
{
public static void main(String args[])
{
Box mybox1 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
double vol;
/* assign different values to mybox2's
//calling the method
vol= mybox1.volume();
System.out.println("the Volume is:"+vol);
}
}
5. METHOD OVERLOADING
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. When Java
encounters a call to an overloaded method, it simply executes the version of the method
whose parameters match the arguments used in the call.
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
6. CONSTRUCTORS
It can be tedious to initialize all of the variables in a class each time an instance is
created. Even if we use some method to initialize the variables, it would be better this
initialization is done at the time of the object creation.
Example Program:
class Box
{
double width;
double height;
double depth;
Parameterized Constructors
Constructor can have parameters. Constructor with parameters is called Parameterized
Constructor.
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
7. CONSTRUCTOR OVERLOADING
In Java it is possible to define two or more class constructors that share the same name, as
long as their parameter declarations are different. This is called constructor overloading.
When an overloaded constructor is invoked, Java uses the type and/or number of
arguments as its guide to determine which version of the overloaded constructor to actually call.
Thus, overloaded constructors must differ in the type and/or number of their parameters.
Example: All the constructors names will be same, but their parameter list is different.
OverloadCons.java
class Box {
double width;
double height;
double depth;
class OverloadCons
{
public static void main(String args[])
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
8. GARBAGE COLLECTION
Objects are dynamically allocated in Java by using the new operator. In some languages,
such as C++, dynamically allocated objects must be manually released by use of a delete
operator. But, Java takes a different approach; it handles deallocation automatically. The
technique that accomplishes this is called garbage collection.
There are Two Techniques: 1) Reference Counter 2) Mark and Sweep.
Reference Counter: In the Reference Counter technique, when an object is created along with it
a reference counter is maintained in the memory. When the object is referenced, the reference
counter is incremented by one. If the control flow is moved from that object to some other
object, then the counter value is decremented by one. When the counter reaches to zero (0), then
it's memory is reclaimed.
Mark and Sweep: In the Mark and Sweep technique, all the objects that are in use are marked
and are called live objects and are moved to one end of the memory. This process we call it as
To add a finalizer to a class, you simply define the finalize( ) method. Inside the
finalize() method, you will specify those actions that must be performed before an object is
destroyed.
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
Syntax
Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class
and the class Inner_Demo is the nested class.
class Outer{
class Nested
{
// body of the Inner class
}
//body of the outer class
}
Syntax
class MyOuter
{
static class Nested_Demo
{
}
}
Example program:
Outer.java Output
public class Outer
{ D:\>javac Outer.java
//inner static class D:\>java Outer
static class Nested_Demo This is my nested class
{
public void my_method()
{
System.out.println("This is my nested class");
}
}
//body of outer class
public static void main(String args[])
{
//without creating the object of outer class
Outer.Nested_Demo nested = new
Outer.Nested_Demo();
nested.my_method();
}
}
Creating an inner class is quite simple. You just need to write a class within a class.
Unlike a class, an inner class can be private and once you declare an inner class private, it
cannot be accessed from an object outside the class.
Following is the program to create an inner class and access it. In the given example, we make
the inner class private and access the class through a method.
Example program:
The keyword final is a non-access modifier. The java final keyword can be used in many
context. Final can be:
1. variable
2. method
3. class
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Example:
class Main {
public static void main(String[] args) {
n the above program, we have created a final variable named age. And we have tried to change
the value of the final variable.
When we run the program, we will get a compilation error with the following message.
Example:
class FinalDemo {
// create a final method
public final void display() {
System.out.println("This is a final method.");
}
}
In the above example, we have created a final method named display() inside
the FinalDemo class. Here, the Main class inherits the FinalDemo class.
We have tried to override the final method in the Main class. When we run the program, we will
get a compilation error with the following message.
In Java, the final class cannot be inherited by another class. For example,
// create a final class
final class FinalClass {
public void display() {
System.out.println("This is a final method.");
}
}
In the above example, we have created a final class named FinalClass. Here, we have tried to
inherit the final class by the Main class.
When we run the program, we will get a compilation error with the following message.
If we call a method passing a any primitive value, it is known as pass by value. The
changes being done in the called method, is not affected in the calling method.
In case of call by reference original value is changed if we made changes in the called
method. If we pass object reference in place of any primitive value, original value will be
changed.
class Operation
{
int data=50;
void change(int data)
{
data=data+100;//changes will be in the local variable only
}
In case of pass by reference original value is changed if we made changes in the called method. If we
pass object reference in place of any primitive value, original value will be changed.
In this example we are passing object reference as a value. Let's take a simple example:
class Operation2
{
int data=50;
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.
Note: This is mainly used to hide the local variables from the instance variable.
Example:
class Box
{
//instance variable
double width, height, depth;
Box(double width, double height, double depth)
{
//local variables are assigned, but not the instance variable
width=width;
height=height;
depth=depth;
}
Example:
Output:
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
When a member is declared static, it can be accessed without reference to any object.
You can declare both methods and variables to be static.
Static Variables: Static variables are shared by all the objects. These variables are also called as
"Class Variable".
Static block: If you need to do computation in order to initialize your static variables, you can
declare a static block that gets executed exactly once, when the class is first loaded.
The following example shows a class that has a static method, some static variables, and
a static initialization block:
class UseStatic
{
//static variable
static int a = 3;
static int b;
//static method
static void meth(int x)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
//static block
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[])
{
//static methods are called without object
meth(42);
}
}
Note: Static blocks are executed first, even than the static methods. Static methods can be
called without object.
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
import java.util.*;
class ATM
{
static float balance;
void deposit()
Recursion in java is a process in which a method calls itself continuously. A method in java that
calls itself is called recursive method.
Syntax:
returntype methodname(){
//code to be executed
methodname();//calling same method
}
Output:
factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120
Java is strictly pass-by-value language. When we pass a primitive type to a method, the method
receives a copy of the value. However, when we pass an object to a method, the method receives
a reference to the object. When we made changes to the object inside the method will be
reflected in the object outside the method.
Basically, a parameter cannot be changed by the function, but the function can ask the parameter
to change itself via calling some method within it.
o While creating a variable of a class type, we only create a reference to an object. Thus,
when we pass this reference to a method, the parameter that receives it will refer to the
same object as that referred to by the argument.
o It means that objects act as if they are passed to methods by use of call-by-reference.
o Changes to the object inside the method do reflect the object used as an argument.
ObjectPassing.java
class ObjectPassDemo {
int a, b;
// Constructor
ObjectPassDemo(int i, int j)
{
a = i;
b = j;
}
boolean equalTo(ObjectPassDemo o)
{
// Returns true if o is equal to the invoking
// object notice an object is passed as an
// argument to method
return (o.a == a && o.b == b);
}
}
public class ObjectPassing {
public static void main(String args[])
{
// Creating object of above class inside main()
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);
// Checking whether object is equal as custom values
// above passed and printing corresponding boolean value
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
}
}
******************************************