Chapter 2 Classes and Objects
Chapter 2 Classes and Objects
Chapter 2 Classes and Objects
Chapter Three
Classes and Objects in Java
OOP Principles
Class is an OOP construct that consists of data members and member functions. Data
members are nothing but simply variables that we declare inside the class so it called data
member of that particular class. Member functions are the function or you can say method
which we declare inside the class so it is called member function of that particular class. The
most important thing to understand about a class is that it defines a new user
defined/programmer defined data type. Once defined, this new data 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.
When we consider a Java program, it can be defined as a collection of objects that communicate
via invoking each other's methods. Let us now briefly look into what do class, object, methods,
and instance variables mean.
Object - Objects have states and behaviors. Example: An object is an instance of a class.
Class - A class can be defined as a template/blueprint that describes the behavior/state
that the object of its type supports.
Methods - A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are
executed.
Instance Variables - Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.
Syntax of class:
class classname
{
type instance-variable1;
type instance-variable2;
//....
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
// ...
type methodnameN(parameter-list)
{
// body of method }}
1
Classes and Objects in Java
Instantiation
When you define a class, you declare its exact form and nature/template. You do this by
specifying the data that it contains and the code that operates on that data. The data, or
variables, defined within a class are called instance variables. The code is contained within
methods.
void displayPoint()
{
System.out.println("Printing the coordinates");
System.out.println(x + " " + y);
}
public static void main(String args[])
{
MyPoint obj; // declaration
obj = new MyPoint(); // allocation of memory to an object
obj.x=10; //access data member using object.
obj.y=20;
obj.displayPoint(); // calling a member method
}
}
Output :
Printing the coordinates
10 20
Here x and y are data members of class MyPoint and displayPoint() is a member function
of the same class. In above program we can take as many objects as we want. From the above
program one thing we should keep in mind that when we want to access data member or
methods of class we have to write objectname.member name(dot operator)
Syntax:
accessing data member of the class: objectname.datamember name;
accessing methods of the class: objectname.method name();
So for accessing data of the class: we have to use (.) dot operator.
NOTE: we can use or access data of any particular class without using (.) dot operator from
inside that particular class only.
The program in above topic can easily show that how object is going to be declared and
defined for any class.
Syntax of object:declaration
2
Classes and Objects in Java
3
Classes and Objects in Java
width, and height. It is important to understand that changes to the instance variables of
one object have no effect on the instance variables of another.
Assigning Object Reference Variables :
Suppose
Box b1 = new Box();
Box b2 = b1;
Here b1 is the object of class Box. And we assign b1 to b2 by b2=b1.Here we did not use
new keyword for b2 so 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.
NOTE: When you assign one object reference variable to another object reference variable,
you are not creating a copy of the object, you are only making a copy of the reference. As we all
know that, classes usually consist of two things instance variables and methods.
Here we are going to explain some fundamentals about methods. So we can begin to add
methods to our classes
.
Class Methods
Methods are defined in a class body using the components as below
Return type
Name of the method
A list of parameters
Body of the method.
Syntax:
return type method name (list of parameters)
{
Body of the method
}
return type specifies the type of data returned by the method after manipulation. This can
be any valid data type including class types that you create. If the method does not return a value,
its return type must be void, Means you can say that void means no return. 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.
The method name is any legal identifier.
The list of parameter 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.
4
Classes and Objects in Java
Let us look at one example of class which have methods and data members both.
import java.util.Scanner;
class Box
{
double width;
double height;
double depth;
void volume() // display volume of a box
{
System.out.print("Volume is : ");
System.out.println(width * height * depth);
}
}
class BoxDemo
{
public static void main(String args[])
{
Box box1 = new Box(); // defining object box1 of class Box
Scanner s = new Scanner(System.in);
System.out.print(“Enter Box Width : ”);
box1.width = s.nextDouble();
System.out.print(“Enter Box Height : ”);
box1.height = s.nextDouble();
System.out.print(“Enter Box Depth : ”);
box1.depth = s.nextDouble();
// display volume of box1
box1.volume(); // calling the method volume
}
}
Output:
Enter Box Width : 15
Enter Box Height : 20
Enter Box Depth : 10
Volume is : 3000.00
Here width, height and depth are data members of class Box and void volume() is method
of class Box. Here method has no parameter and no return value.
Now let us look at same program but in different way.
import java.util.Scanner;
class Box
5
Classes and Objects in Java
{
double width;
double height;
double depth;
double volume()
{
return width * height * depth;
}
}
class BoxDemo
{
public static void main(String args[])
{
double vol;
Box box1 = new Box(); // defining object box1 of class Box
Scanner s = new Scanner(System.in);
System.out.print(“Enter Box Width : ”);
box1.width = s.nextDouble();
System.out.print(“Enter Box Height : ”);
box1.height = s.nextDouble();
System.out.print(“Enter Box Depth : ”);
box1.depth = s.nextDouble();
// display volume of box1
vol = box1.volume(); // calling the method volume
System.out.println("Volume is : " +vol);
}
}
Output:
Enter Box Width : 15
Enter Box Height : 20
Enter Box Depth : 10
Volume is : 3000.00
Here in above program volume() method has return type double so we took one vol
variable. It is a local variable of class BoxDemo and it catch the returned value by volume
method of class Box. One thing must keep in mind that the data type of vol and return type of
volume() method always be same.
import java.util.Scanner;
class Box
{
double width;
6
Classes and Objects in Java
double height;
double depth;
double volume(double w, double h, double d)
{
return width * height * depth;
}
}
class BoxDemo
{
public static void main(String args[])
{
double vo,wth,ht,dth;
Box box1 = new Box(); // defining object box1 of class Box
Scanner s = new Scanner(System.in);
System.out.print(“Enter Box Width : ”);
wth = s.nextDouble();
System.out.print(“Enter Box Height : ”);
ht = s.nextDouble();
System.out.print(“Enter Box Depth : ”);
dth = s.nextDouble();
// display volume of box1
vol = box1.volume(wth,ht,dth); // calling the method volume
System.out.println("Volume is : " +vol);
}}
Output:
Enter Box Width : 15
Enter Box Height : 20
Enter Box Depth : 10
Volume is : 3000.00
Here in above program volume() method has three parameters as well as double return type.
Here we took three extra local variables in class BoxDemo and pass them in function calling.One
thing must keep in mind that in defining and calling of method, the sequence of data type of
parameter must be same in both. Java supports a special type of methods, called constructor that
enables an object to initialize itself when it is created.
Constructors
Constructors are special member methods that have the same name as the class it-self.
Constructors do not have specific return type and not even void. This is because they return the
instance of the class itself. A constructor is automatically called when an object is created.
Syntax:
Constructor_name([arguments])
7
Classes and Objects in Java
{
// body
}
Constructors are generally of two types.
1. Non-Parameterized
2. Parameterized
1. Non-Parameterized:
// Non - parameterised constructor / default constructors
class Point1
{
int x;
int y;
Point1() //constructor of class
{
x = 10;
y = 20;
}
void display()
{
System.out.println("\n\n\t-----Printing the coordinates-----");
System.out.println("\t\t\t" + x + " " + y);
}
}
class pointDemo
{
public static void main(String args[])
{
Point1 p1 = new Point1(); // constructor will be call automatically from here
p1.display();
}
}
Output:
-----Printing the coordinates-----
10 20
2. Parameterized:
// parameterised constructor
import java.util.Scanner;
class Point2
8
Classes and Objects in Java
{
int x;
int y;
Point2(int a, int b)
{
x = a;
y = b;
}
void display()
{
System.out.println("\n\n\t-----Printing the coordinates-----");
System.out.println("\t\t\t" + x + " " + y);
}
}
class pointDemo
{
public static void main(String args[])
{
int i,k;
Scanner s = new Scanner(System.in);
System.out.print("Enter int value for i : ");
i = s.nextInt();
System.out.print("Enter int value for k : ");
k = s.nextInt();
Point2 p1 = new Point2(i,k);
p1.display();
}
}
Output:
Enter int value for i : 10
Enter int value for k : 20
-----Printing the coordinates-----
10 20
We have already seen several keywords so far. But here we are going to learn few regularly used
keywords. new, this, static, super, final
The super and final keywords will demonstrate in further chapter.
new:
The new keyword dynamically allocates memory for an object.
Syntax:
class_name object _name = new class_name();
9
Classes and Objects in Java
EX.
Box b1 = new Box();
Box b2 = new Box();
We have already seen so many programs in which we used new keyword for creating objects.
this:
This keyword is the name of a reference that refers to a calling object itself. One common
use of the this keyword is to reference a class hidden data fields. You can have local variables,
including formal parameters to methods which overlap with the names of the class` instance
variables. The local variable hides the instance variable so we use this keyword. Another
common use of this keyword is to enable a constructor to invoke another constructor of the same
class. Java requires that the this(arg-list) statement appear first in the constructor before any
other statements.
EX :
public class This_demo
{
public static void main(String[] args)
{
abc a1 = new abc(); //call non parameterize constructor
}
}
class abc
{
int x,y;
abc()
{
this(10,20); //this will call another constructor
}
abc(int x,int y)
{
this.x=x+5; //it will set class` member x
this.y=y+5; //it will set class` member y
System.out.println("local method`s x = " +x);
System.out.println("local method`s y = " +y);
Print_data();
}
public void Print_data()
{
System.out.println("x = " +x);
System.out.println("y = " +y);
}
10
Classes and Objects in Java
Output :
local method`s x = 10
local method`s y = 20
x = 15
y = 25
static :
A class member must be accessed with the use of an object of its class but sometimes we
want to define a class member that will be used independently without creating any object of that
class. It is possible in java to create a member that can be used by itself, without reference to a
specific instance. To create such a member, precede its declaration with the keyword static.
When a member is declared static, it can be accessed before any objects of its class are created,
and without reference to any object. One 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 object exist. Instance variables declared as static are actually, global
variables. When objects of its class are declared, no copy of a static variable is made. Instead, all
instances of the class share the same static variable.
Method declared as static have several restrictions:
1. Can call only other static methods.
2. Only access static data.
3. Cannot refer to this
One can also declare a static block which gets executed exactly once, when the class is first
loaded.
EX :
public class Static_Demo
{
public static void main(String[] args)
{
display(40); //call static method
}
static int i = 5;
static int j;
int k = 10;
static void display(int a)
{
System.out.println("a = "+a);// here a = 40
System.out.println("i = "+i); // here i = 5
System.out.println("j = "+j);
// here j = 50( because of static block j = i * 10 = 5 * 10 =50
)
System.out.println("k = "+k);
11
Classes and Objects in Java
Encapsulation
One can control what parts of a program can access the member of a class. By controlling access,
one can prevent misuse. For Example, allowing access to data only through a well-defined set of
methods, one can prevent misuse of that data. Thus, when correctly implemented, a class creates
“black box”. How a member can be accessed is determined by the access specifier that modifies
its declaration. Java provides a set to access specifiers. Some aspects of access control are related
to inheritance or packages.
public:
When a member of a class is specified by the public specifier, then that member can be
accessed by any other code.
The public modifier makes a method or variable completely available to all classes.
Also when the class is defined as public, it can be accessed by any other class.
private:
protected:
12
Classes and Objects in Java
13
Classes and Objects in Java
an overloaded method, it simply executes the version of the method whose parameters match the
arguments used in the call.
EX :
public class MethodOver
{
int n1;
int n2;
MethodOver()
{
n1 = 10;
n2 = 20;
}
void square()
{
System.out.println("The Square is " + n1 * n2);
}
void square(int p1)
{
n1 = p1;
System.out.println("The Square is " + n1 * n2);
}
void square(int p1, int p2)
{
n1 = p1;
n2 = p2;
System.out.println("The Square is " + n1 * n2);
}
public static void main(String args[])
{
MethodOver obj1 = new MethodOver();
obj1.square(); //call non parameterise method
obj1.square(4); //call method which has 1 argument
obj1.square(7,8); //call method which has 2 argument
}
}
Output :
14
Classes and Objects in Java
You can see that here we have 3 square methods with different argument. It's called method
overloading. Constructor overloading in java: Along with method overloading, we can also
overload constructors. Constructors having the same name with different parameter list is called
constructor overloading.
EX :
class Point
{
int x;
int y;
Point(int a, int b)
{
x = a;
y = b;
}
}
class Circle
{
int originX;
int originY;
int radius;
//Default Constructor
Circle()
{
originX = 5;
originY = 5;
radius = 3;
}
// Constructor initializing the coordinates of origin and the radius.
Circle(int x1, int y1, int r)
{
originX = x1;
originY = y1;
radius = r;
}
Circle(Point p, int r)
{
originX = p.x;
originY = p.y;
radius = r;
}
15
Classes and Objects in Java
void display()
{
System.out.println("Center at " + originX + " and " + originY);
System.out.println("Radius = " + radius);
}
public static void main(String args[])
{
Circle c1 = new Circle();
Circle c2 = new Circle(10,20,5);
Circle c3 = new Circle(new Point(15,25),10);
c1.display();
c2.display();
c3.display();
}
}
Output :
--Center at 5 and 5
Radius = 3
--Center at 10 and 20
Radius = 5
--Center at 15 and 25
Radius = 10
Above program is quite complicated here i am giving you perfect flow of program. First of all
note one thing that new ClassName() this is a short syntax of creating object of any class. And
we all know that when we create object the constructor of that class will be called automatically.
So in our program first of all due to syntax Circle c1 = new Circle(); non
parameterize constructor will be called for object c1 so we get output like Center at 5 and 5
Radius = 3 in c1.display(). Next due to syntax Circle c2 = new Circle(10,20,5); constructor
which has 3 arguments will be called for object c2 so we get output like Center at 10 and 20
Radius = 5 in c2.display(). Now when we define object c3 our syntax is like Circle c3 = new
Circle(new Point(15,25),10); so first of all it will create object for Point class so constructor of
point class will be called and it will set parameter x and y. Then constructor of circle class which
has Point class object as an argument along with one int argument will be called and set all
parameter as per program and we get output like Center at 15 and 25 Radius = 10 in c3.display().
We can also write
Point p1 = new Point(15,25);
Circle c3 = new Circle(p1,10);
This is how we can pass object as an argument in constructor. We have already seen Call by
reference in which we pass object as a method argument. Now in next topic we will discuss about
how you can return an object.
16