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
Class Fundamentals:
Defining class in JAVA
• class is a Keyword.
• class is a collection of fields, methods, constructors and certain properties.
• class acts like a blueprint.
• When defining class, it should start with keyword class followed by name of the class; and the
class body, enclosed by a pair of curly braces.
Syntax:
class class_name
{
type instance-variable1;
type instance-variable2;
type instance-variableN; //variables(fields or members)
type methodname1(parameter-list) //method(member function)
{
// body of method
}
type methodname2(parameter-list) //method(member function)
{
// body of method
}
}
Look at the following picture to understand the class and object concept.
• 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.
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;
[Link]=10;
[Link]=10;
[Link]=15;
vol=[Link] * [Link] * [Link];
[Link]("volume is "+vol);
}
}
• Class defines a new type of data.
• In the above example, mybox will be an instance of box. Thus, every box object will
containits own copies of the instance variables width, height and depth.
• Dot (.) operator is used to access the variables. The dot operator links the name of the
object with the name of the instance variable.
Example :
[Link]=100;
//program declares two box objects.
package mypack;
public class box
{
double width; Output:
double height; Volume is 3000.0
//creates only a template Volume is 162.0
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;
[Link]=10;
[Link]=20;
[Link]=15;
[Link]=3;
[Link]=6;
[Link]=9;
vol=[Link]*[Link]*[Link];
//volume of first box
[Link]("volume is "+vol);
vol=[Link]*[Link]*[Link];
//volume of first box
[Link]("volume is "+vol);
}
}
Declaring object:
<ClassName> <objectName> = new <ClassName>( );
Object Instantiation
• Object is an instance of the class or blueprint of class.
• Object is used to access members and member functions.
• When you create a class, you are creating a new data type.
• Object is created using new keyword, which allocates the memory for object when it
is 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.
• Thus, in Java, all class objects must be dynamically allocated.
• To declare an object of type Box: Box mybox = new Box( );
• This statement combines the two steps just described. It can be rewritten like this to show each
step more clearly:
Step1: Box mybox; // declare reference to object
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.
Step 2: mybox = new Box(); // allocate a Box object
width
height
mybox
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 alias name for object.
➢ Object reference variables act differently than you might expect when an assignment
takes place.
Box b1=new Box( ) ;
Box b2=b1 ;
• 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:
• A method is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are also known as functions.
• Why use methods? To reuse code: define the code once, and use it many times.
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header, as we have
shown in the following figure.
Following are the elements of a method –
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.
Advantage of Method:
• Code Reusability
• Code Optimization
We can write method in different ways depends on return value –
Writing method –
o Without parameters and without return value.
o Without parameters and with a return value.
o With parameters and without return value.
o With parameters and with return value.
Without parameters and without return value:
In this type A Method will not accept any parameters and not return any value to the Main
method.
public class box
{
double width, height, depth;
//display volume of a box
Void volume()
// Method Without parameters without return value.
[Link](“volume is “);
[Link](width*height*depth);
}
}
class boxdemo1
{
public static void main(String[] args)
{
box mybox1=new box();
[Link]=10;
[Link]=20;
[Link]=15;
[Link]();
}
}
Without parameters and with a return value:(Returning a value)
In this type A Method will not accept any parameters and return value to the Main method.
//Now, volume() returns the volume of a box
public class box
{
double width, height, depth;
//display volume of a box
double volume() // Method Without parameters with return value.
{
return width*height*depth;
}
}
class boxdemo1
{
public static void main(String[] args)
{
box mybox1=new box();
double vol;
[Link]=10;
[Link]=20
;
[Link]=15;
vol=[Link](
);
[Link]("volume is "+vol);
}
}
There are two important things to understand about the returning values:
1) 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 same method is Boolean, you could
not return an integer.
2) 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.
With parameters and without return value:
➢ In this type A Method will accept parameters but not return value to the Main method.
package mypack;
public class box
{
Public void volume(double weight,double height,double depth)
{
double vol;
vol=weight*height*depth;
[Link]("volume is: " +vol );
}
public static void main(String[] args)
{
box mybox1 = new box( ) ;
[Link](20,30,10) ;
}
}
With parameters and with return value:
➢ In this type A Method will accept parameters and return value to the Main method.
class box
{
public double volume(double weight,double height,double depth)
{
double vol;
vol=weight*height*depth;
return vol;
}
public static void main(String[] args)
{
box mybox1 = new box( ) ;
double vol =[Link](20,30 ,10) ;
[Link]("volume is: " +vol );
}
}
Constructors
• A constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in
the memory.
• It is a special type of method which is used to initialize the object.
• 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.
Note: It is called constructor because it constructs the values at the time of object creation. It is not
necessary to write a constructor for a class. It is because java compiler creates a default constructor
if your class doesn't have any.
Rules for creating Java constructor
1. Constructor name must be the same as its class name
2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Note: We can use access modifiers while declaring a constructor. It controls the object creation.
Types of Java constructors
There are two types of constructors in Java:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.
Syntax of default constructor:
Class <class_name>{
Return_type <class_name>(){
}
}
Example of default constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time
of object creation.
//Java Program to create and call a default constructor
class Bike1
{
//creating a default constructor
Bike1()
{
[Link]("Bike is created");
}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output:
Bike is created
Rule: If there is no constructor in a class, compiler automatically creates a default constructor.
Q) What is the purpose of a default constructor?
The default constructor is used to provide the default values to the object like 0, null, etc., depending
on the type.
Example of default constructor that displays the default values
//Let us see another example of default constructor
//which displays the default values
class Student3
{
int id;
String name;
//method to display the value of id and name
void display()
{
[Link](id+" "+name);
}
public static void main(String args[])
{
//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
[Link]();
[Link]();
}
}
Output:
0 null
0 null
Explanation:
In the above class, you are not creating any constructor so compiler provides you a default
constructor. Here 0 and null values are provided by default constructor.
Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized constructor.
Why use the parameterized constructor?
The parameterized constructor is used to provide different values to distinct objects. However, you
can provide the same values also.
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){
[Link](id+" "+name);
}
public static void main(String args[]){
//creating objects and passing values
Student4 s1 = new Student4(111,"Prajwal");
Student4 s2 = new Student4(222,"Pooja");
//calling method to display the values of object
[Link]();
[Link]();
}
}
Output:
111 Prajwal
222 Pooja
Constructor Overloading in Java
In Java, a constructor is just like a method but without return type.
It can also be overloaded like Java methods.
Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists.
They are arranged in a way that each constructor performs a different task.
They are differentiated by the compiler by the number of parameters in the list and their types.
Example of Constructor Overloading
//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i, String n, int a){
id = i;
name = n;
age=a;
}
void display(){
[Link](id+" "+name+" "+age);
}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
[Link]();
[Link]();
}
}
Output:
111 Karan 0
222 Aryan 25
Difference between constructor and method in Java
There are many differences between constructors and methods. They are given below.
Java Constructor Java Method
A constructor is used to initialize the state A method is used to expose the
of an object. behaviour of an object.
A constructor must not have a return type. A method must have a return type.
The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a default
The method is not provided by the
constructor if you don't have any
compiler in any case.
constructor in a class.
The constructor name must be same as the The method name may or may not be
class name. same as the class name.
Java Copy Constructor
There is no copy constructor in Java. However, we can copy the values from one object to another
like copy constructor in C++.
There are many ways to copy the values of one object into another in Java. They are:
o By constructor
o By assigning the values of one object into another
o By clone() method of Object class
In this example, we are going to copy the values of one object into another using Java constructor.
//Java program to initialize the values from one object to another object.
class Student6{
int id;
String name;
//constructor to initialize integer and string
Student6(int i,String n){
id = i;
name = n;
}
//constructor to initialize another object
Student6(Student6 s){
id = [Link];
name =[Link];
}
void display(){[Link](id+" "+name); }
public static void main(String args[]){
Student6 s1 = new Student6(111,"Karan");
Student6 s2 = new Student6(s1);
[Link]();
[Link]();
}
}
Output:
111 Karan
111 Karan
Copying values without constructor
We can copy the values of one object into another by assigning the objects values to another object.
In this case, there is no need to create the constructor.
class Student7{
int id;
String name;
Student7(int i, String n){
id = i;
name = n;
}
Student7(){}
void display(){[Link](id+" "+name);}
public static void main(String args[]){
Student7 s1 = new Student7(111,"Karan");
Student7 s2 = new Student7();
[Link]=[Link];
[Link]=[Link];
[Link]();
[Link]();
}
}
Output:
111 Karan
111 Karan
What is the purpose of Constructor class?
Java provides a Constructor class which can be used to get the internal information of a constructor
in the class. It is found in the [Link] package.
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.
Box(double width, double height, double depth)
{
[Link] = width;
[Link] = height;
[Link] = depth;
}
Example Program: -
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display(){[Link](rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
[Link]();
[Link]();
}
}
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
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.
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)
{
[Link](a+b);
}
Output:
public void Addition( int a, int b,int c) 30
{ 60
[Link](a+b+c);
}
public static void main(String[] args){
First obj = new First( ) ;
[Link] (10, 20);
[Link](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 both correct and common to pass objects to methods
public class test{
int a,b;
test(int i,int j)//parameterized constructor
{
a=i;
b=j;
boolean equals(test o) //passing object as parameter
{
if(o.a==a && o.b==b)
{
return true;
}
else
return false;
}
}
public class passob {
public static void main(String[] args){
test ob1=new test(10,20);
test ob2=new test(10,20);
test ob3=new test(-1,-1);
[Link]("ob1==ob2" + [Link](ob2));
[Link]("ob1==ob3" + [Link](ob3));
}
}
}
Output:
ob1==ob2 true
ob1==ob3 false
Argument passing in java:
Arguments passing in Java refers to the mechanism of transferring data between methods or
functions. Arguments in Java are always passed-by-value.
Java supports two types of arguments passing techniques
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
variableswhich are copies of each other. Any changes to one variable don’t modify the other.
Output:
original value.
public class test
{
void meth(int i,int j) Output:
{ a and b before call:15 20a
i*=2; and b after call:15 20
j/=2;
}
}
class callbyvalue
{
public static void main(String[] args)
{
test ob=new test();
int a=15,b=20;
[Link]("a and b before call: " +a + "" +b);
[Link](a,b);
[Link]("a and b after call: " +a +" " +b);
}
}
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.
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.
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 tengreater than it is in the invoking object.
Recursion:
➢ Recursion is the process of defining something in terms of itself.
➢ A method in java that calls itself is called recursive method.
➢ When writing recursive methods, you must have an if statement somewhere to force the
methodto return without the recursive call being executed.
➢ The main advantages of recursive methods is that to create clearer and simpler versions
ofseveral algorithms than can their iterative functions.
Example: factorial of a number
class factorial
{
int fact(int n)
{
int result; Output:
if(n==1) Factorial of 5 is:120
return 1; Factorial of 4 is:24
else Factorial of 3 is:6
result=n * factorial(n-1);
return result;
}
}
class recursion
{
public static void main(String[] args)
{
factorial f= new factorial();
[Link]("Factorial of 5 is: "+factorial(5));
[Link]("Factorial of 4 is: "+factorial(4));
[Link]("Factorial of 3 is: "+factorial(3));
}
}
Access Modifiers (Access Specifiers or Access Control)
➢ Access control controls which parts of the code access the members of a class.
➢ By controlling the access, you can prevent misuse of the data.
➢ The access modifier’s in Java specifies the accessibility or scope of a field, method,
constructor, orclass.
➢ We can change the access level of fields, constructors, methods, and class by applying the
accessmodifier on it.
Types:
❖ Default
❖ Public
❖ Private
❖ Protected
Within Within Outside Package By Outside
Access Modifier
Class Package Subclass Only Package
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
outsidethe 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. Itcan'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
private int c;// private access
void setc(int i)
{
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
[Link](100);;
[Link]("a,b,and c:"+ob.a +"" + ob.b + "" + [Link]());
}
}
Nested and Inner Classes:
➢ It is possible to define a class within another class; such classes are known as nested classes.
➢ The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is
defined within class A, then B does not exist independently of A.
➢ The most important type of nested class is the inner class. An inner class is a non-static nested
class. It has 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.
➢ The inner class does not have exist independently of outer class.
➢ The following program illustrates how to define and use an inner class.
public class Temp
{
int a=10;
class inner
{
void display( )
{
[Link]("value of a is "+a);
}
}
void test( )
{
inner obj=new inner();
[Link]();
} Output:
public static void main( String args[ ] ) value of a is 10
{
Temp obj=new Temp();
[Link]();
}
}
Qp) What are the uses of final, explain with examples?
• A variable can be declared as final.
• Final variable is initialized when it is declared.
• It is a common coding convention to choose all uppercase identifiers for final
variables.
• A final variable is like a constant.
• The keyword final has three uses.
a. It can be used to create the equivalent of a named
constant.
b. to Prevent Overriding
c. to Prevent Inheritance
create the equivalent of a named constant:
example:
final float PI=3.141f;
final int MAX=10;
final int FILE_NEW=1;
final int FILE_OPEN=2;
PREPARED BY: -
Professor. B. Praveen Kumar. M.E., [Link]., PG Dip in Karate., MA.,[Link]., (PhD).