Java Notes 4 (Class and Object)
Java Notes 4 (Class and Object)
If you have done any kind of programming and you are given a problem like, calculate the total pay of an
employee by adding the salary and bonus, how would you do it. so we will have something like below:
so given a situation, where we have the employee salary and bonus, we will add salary and bonus and
print the total pay.
Or
We would call a method or subroutine here
------------------------------
CalculateTotalPay()
{
totalPay = salary + bonus;
}
------------------------------
So here if you notice, we are taking the input of salary and bonus and then we are calling some kind of
function or subroutine to calculate total pay and then this function will calculate the total pay and print
the total pay:
-----------------------------
input salary, bonus;
call Function CalculateTotalPay()
print totalPay;
-----------------------------
This is the old way of writing the program. A kind of a top down approach. It starts from top to bottom ,
and then you run this program again and again for various employees. Like for an employee named
akshay who will take some Salary and bonus you will call this function which will calculate the total pay
and then print the total pay for akshay. For laxmi we will run the program again and for some other
employee abc.
But in object oriented programming, the same program of calculating total pay is written in a different
manner.
class Employee
{
1
Now this class will have those two data, i.e. salary and bonus. and then it will have a function or method
calculateTotalPay() which will calculate the total pay by adding the salary and bonus.
class Employee
{
double salary;
double bonus;
CalculateTotalPay()
{
totalPay = salary + bonus;
print totalPay
}
}
Now in some other place, we will have some kind of a main method, where we will create employees
like below:
main()
{
Employee akshay, laxmi, ritesh;
}
So just like int x,y,z; we also have Employee akshay, laxmi , ritesh;
Same way when you say Employee akshay, laxmi, ritesh, that means,
2
So what does it mean by holding an Employee?
And since Employee has a method calculateTotalPay() akshay will also have calculateTotalPay() method,
akshay.calculateTotalPay();
When akshay calls this calculateTotalPay() method, it will call the CalculateTotalPay() method present in
Employee class and it will add up the salary and bonus, but whose salary and bonus it will add?,
Since akshay is the person who calls this method, it will add akshay's salary and bonus i.e. 90000+20000
and it will print 110000.
akshay.salary = 90000;
akshay.bonus = 20000;
akshay.calculateTotalPay();
Same way for laxmi, laxmi will have her own Employee. i.e. laxmi is a type of Employee so laxmi will have
access to her own salary her own bonus and she can call her own calculateTotalPay()
ie.
laxmi.salary = 100000;
laxmi.bonus = 20000;
laxmi.calculateTotalPay();
So when laxmi calls calculateTotalPay(), it will come to Employee class and it will add salary bonus.
whose salary and bonus? since laxmi is the one who called this method, it will add laxmi's salary and
bonus and print 120000
3
So what is an object ?
An object can be defined as a copy of a class.
Similarly , Since laxmi is a type of Employee, i.e. laxmi is a copy of employee, laxmi will have her own
salary, bonus and calculateTotalPay method.
Object is a copy of a class. Some people also call object as an instance of a class.
So same way, Class is nothing but a template. you create copy of this class Employee and then you are
assigning your own data for each and every object.
class Employee
{
//This is called as data
double salary;
double bonus;
4
Class can have multiple data and multiple methods.
This time we will have a class called Box which will have two data length and breadth and it will have a
method calculateArea() which basically multiply length and breadth and print the area.
-------------------
class Box
{
int length;
int breadth;
calculateArea()
{
int area = length * breadth;
print area;
}
}
--------------------
To make use of this class, we need to create objects of this class.
Below we have created two objects of the Box class
--------------------
main()
{
Box ups, fedEx;
}
--------------------
Since ups is a type of box, ups will have its own length and breadth and it's own calculateArea() method
ups.length = 10;
ups.breadth = 5;
ups.calculateArea();
When ups calls this calculateArea() method, it will call the calculateArea() method present in Box class
and it will multiply the length and breadth, but whose length and breadth it will multiply?,
Since ups is the box that calls this method, it will multiply ups's length and breadth i.e. 10 5 and it will
print area 50.
Similarly fedEx will also have it's own length and breadth and calculateArea method.
fedEx.length = 6;
fedEx.breadth = 7;
fedEx.calculateArea();
5
When fedEx calls this calculateArea() method, it will call the calculateArea() method present in Box class
and it will multiply the length and breadth, but whose length and breadth it will multiply?,
Since fedEx is the box that calls this method, it will multiply fedEx's length and breadth i.e. 6 7 and it will
print area 42.
----------------------
main()
{
Box ups, fedEx;
ups.length = 10;
ups.breadth = 5;
ups.calculateArea();
fedEx.length = 6;
fedEx.breadth = 7;
fedEx.calculateArea();
}
------------------------
So this ups and fedEx are called objects so what are objects?
objects are nothing but copies of the class.
each and every objects has a fresh copy of this box class. It has a fresh length variable, fresh breadth
variable and fresh calculateArea method.
And class has data and methods, and it is a template for objects.
6
System.out.println("Total Pay:" + totalPay);
}
}
------------------------------
calculateTotalPay() is giving some kind of an error.
to remove this error you have to put void in front of this method.
What is void ?
The method is printing something right inside the method and its not returning any value.
void means this method is not sending any value anywhere else, just printing the value right here.
--------------------------------
package classAndObjects;
public class Employee
{
double salary;
double bonus;
}
}
---------------------------------
In this main method, we are going to create objects of Employee.
Now to create objects of employee you can do something like this:
7
Employee akshay, laxmi, ritesh;
And then we can initialize each and every object. This is required mandatorily we have to do this.
akshay = new Employee();
laxmi = new Employee();
ritesh = new Employee();
OR
So once you have created these Employee objects akshay laxmi and ritesh, you can assign the salary and
bonus for each and every object and call the calculateTotalPay() for that object.
that means this akshay object has a fresh copy of salary and bonus to which you can assign fresh values.
akshay.salary = 90000;
akshay.bonus = 20000;
akshay.calculateTotalPay()
8
Employee akshay = new Employee();
Employee laxmi = new Employee();
Employee ritesh = new Employee();
akshay.salary = 90000;
akshay.bonus = 20000;
akshay.calculateTotalPay();
}
}
Output :
Total Pay: 110000.0
--------------------------------------------
same thing goes for laxmi and ritesh:
laxmi.salary = 100000.78;
laxmi.bonus = 23456.89;
laxmi.calculateTotalPay();
ritesh.salary = 110000;
ritesh.bonus = 20000;
ritesh.calculateTotalPay();
So laxmi and ritesh will also have their own salary, bonus and laxmi/ritesh can call their own
calculateTotalPay()
--------------------------------------------
package classAndObjects;
public class TestEmployee
{
public static void main(String[] args)
{
/*Employee akshay, laxmi, ritesh;
akshay = new Employee();
laxmi = new Employee();
ritesh = new Employee();*/
9
akshay.salary = 90000;
akshay.bonus = 20000;
akshay.calculateTotalPay();
laxmi.salary = 100000.78;
laxmi.bonus = 23456.89;
laxmi.calculateTotalPay();
ritesh.salary = 110000.98;
ritesh.bonus = 23456.98;
ritesh.calculateTotalPay();
}
}
Output :
Total Pay:110000.0
Total Pay:123457.67
Total Pay:133457.96
-----------------------------------------------------
lets try the Box class example now and create box objects:
---------------------------
package classAndObjects;
public class Box
{
int length;
int breadth;
void calculateArea()
{
int area = length * breadth;
System.out.println("Area: " + area);
}
}
----------------------------
To test this box class, we will create TestBox class with public static void main method.
We will create two objects of Box -- ups and fedEx and assign length breadth and call the calculateArea
method using both objects.
10
package classAndObjects;
public class TestBox
{
public static void main(String[] args)
{
Box ups = new Box();
Box fedEx = new Box();
ups.length = 5;
ups.breadth = 10;
ups.calculateArea();
fedEx.length = 6;
fedEx.breadth = 7;
fedEx.calculateArea();
}
}
Output :
Area: 50
Area: 42
--------------------------------
Some conventions that we need to follow :
1.class name
Class name should always start with a capital letter. This is not a rule. It will work even if your class name
starts with lower case letter. But we need to follow this convention as per global coding standard.
Example :
int abc;
String myName;
int primeNumber;
char yourGrade;
int yourPassingMarks;
11
3. Method name: same as data (variable) names
Example :
add();
addNumbers();
calculateTotalPay();
void calculateArea()
{
int area = length * breadth;
System.out.println("Area: " + area);
}
we saw in this particular method, the return type is void. i.e. this method is not returning anything. Its
printing the area right here.
Now if you go to the main method and imagine you want to fetch the area of ups and fetch the area of
fedEx, and you want to add both the areas.
How will we do it?
We need to access the area of ups but the area of ups is printed inside the method in Box class, but We
need to access this area value in main method.
So to acess this area value in the main method, we need to return the area (printed in the calculateArea
method) to the main method
So here we can return the area to the main method like this,
void calculateArea()
{
int area = length * breadth;
System.out.println("Area: " + area);
return area; //this will throw an error
}
when we write --> return area; this method is now going to return the area back to the main method,
And when you say return area, we have to make sure that, instead of 'void' we will have to put the data
type of the returned variable, since you are returning area which is of type integer, so you will have to
put int as the return type for this method instead of void
12
int calculateArea()
{
int area = length * breadth;
System.out.println("Area: " + area);
return area;
}
//ups.calculateArea();// instead of directly calling the method, we need to assign this method to an
integer variable
So when ups calls this calculateArea() method, in box class,in calculateArea() method, area is printed
and at the same time, this area is returned to the main method and it is stored in this int area1 variable
Same way we will have another area2 variable for fedEx area.
Now we have access to area1 and area2 in the main method so we can write:
Box class :
package classAndObjects;
public class Box
{
int length;
int breadth;
int calculateArea()
{
int area = length * breadth;
System.out.println("Area: " + area);
return area;
}
13
}
-----------------------
TestBox class :
package classAndObjects;
public class TestBox
{
public static void main(String[] args)
{
Box ups = new Box();
Box fedEx = new Box();
ups.length = 5;
ups.breadth = 10;
int area1 = ups.calculateArea();
fedEx.length = 6;
fedEx.breadth = 7;
int area2 = fedEx.calculateArea();
Output :
Area: 50
Area: 42
Total area of ups and fedEx = 92
---------------------
Passing Arguments in a method:
Box class:
---------------------------
package classAndObjects;
public class Box
{
//This length and breadth is a class level data
int length;
int breadth;
14
int calculateArea()
{
int area = length * breadth;
System.out.println("Area: " + area);
return area;
}
}
------------------------------
//This length and breadth is a class level data
Now the question is how to pass values to the methods
Lets pass int x in calculateArea method and multiply it with the area
int calculateArea(int x)
{
int area = length * breadth * x;
System.out.println("Area: " + area);
return area;
}
now in the TestBox we can pass some integer values like below
-----------------------------
public class TestBox
{
public static void main(String[] args)
{
ups.length = 5;
ups.breadth = 10;
int area1 = ups.calculateArea(4); //passed integer value
fedEx.length = 6;
fedEx.breadth = 7;
int area2 = fedEx.calculateArea(2); //passed integer value
sysout("Total area of ups and fedEx = " + (area1 + area2));
}
}
15
Now when ups calls calculateArea -->ups.calculateArea(4), it will pass 4 as x in the Box class, and this x
will get multiplied with area in Box class and value is printed.
Now some times, you will see something like below in the box class:
Now , this calculateArea() is requesting two int numbers length and breadth, so it request two numbers
we have to provide two numbers while calling this method in TestBox class.
------------------------------
public class TestBox
{
public static void main(String[] args)
{
Box ups = new Box();
Box fedEx = new Box();
ups.length = 5;
ups.breadth = 10;
int area1 = ups.calculateArea(4, 3); //we have to pass two numbers as it now
requests two numbers
fedEx.length = 6;
fedEx.breadth = 7;
int area2 = fedEx.calculateArea(2, 5);//we have to pass two numbers as it now requests
two numbers
16
ups.calculateArea() has taken values as 4 and 3, it has passed this value to length and breadth of
calculateArea method in Box class below: and printed area as 12. Same way for fedEx.calculateArea()
So what happened to the previously assigned data shown below in TestBox class before calling these
methods?
for ups:
ups.length = 5;
ups.breadth = 10;
for fedEx
fedEx.length = 6;
fedEx.breadth = 7;
When you pass some arguments, the passing arguments takes precedence over class level data.
When you say
ups.length = 5; you are setting the class level data
But when you pass some data and both of them match like the class level data variable name and the
passing arguments are given same name, then preference will be given to the passing arguments.
You can check this, just double click the variable and it will highlight the reference variable.
Now what if I want to use the class level data, what if i want to use 5 and 10 (class level)and ignore 4 and
3(passed arguments) for ups
17
int area = this.length * this.breadth;
System.out.println("Area: " + area);
return area;
}
When you write this.length and this.breadth; it will take the class level data instead of taking the local
data.
again you can check by highlighting the this.length and this.breadth and it will highlight the class level
variable in Box class.
----------------------------------------------------
//Box class :
package classAndObjects;
public class Box
{
int length; //class level data
int breadth; //class level data
package classAndObjects;
public class TestBox
{
public static void main(String[] args)
{
Box ups = new Box();
Box fedEx = new Box();
18
int area1 = ups.calculateArea(4,3); //this will be ignored
Output :
Area: 50
Area: 42
Total area of ups and fedEx = 92
---------------------
Constructor :
Create another package: day2.Constructor and create a class SmallBox having data length and width and
calculateArea() method.
------------------------
public class SmallBox
{
int length;
int width;
void calculateArea()
{
System.out.println("Area = " + (length * width));
}
}
------------------------
We will test this SmallBox box in another class TestBox:
and we will create object of SmallBox
--------------------------
public class TestBox
{
public static void main(String[] args)
{
SmallBox obj = new SmallBox();
obj.calculateArea();
19
}
}
-----------------------------
using object of SmallBox we can assign values to length and width present in SmallBox.
Now imagine without assigning values, if i call calculateArea method, it will take the default value of
length and width as 0 and 0 and print area as 0. Just run the TestBox class and check.
So like this, we want some default values. For example, we want all boxes of default values 5 as length
and 6 as width.
So what is a constructor :
void calculateArea()
{
System.out.println("Area = " + (length * width));
}
}
------------------------------
in this constructor we have assigned default values to class level data i.e. length and width
20
SmallBox()
{
this.length = 5;
this.width = 6;
System.out.println("Constructor fired");
}
We have added print statement "Constructor fired" so that we will knw when exactly this method
executed.
Now go back to TestBox class and run it
-------------------------
public class TestBox
{
public static void main(String[] args)
{
SmallBox obj = new SmallBox();
obj.calculateArea();
}
}
Output :
Constructor fired
Area = 30
--------------------------
Constructor got executed when the object of SmallBox is created in the TestBox main method.
SmallBox obj = new SmallBox(); --> When this line got executed the constructor got automatically
executed
So in this constructor you are setting the length and width and printing "constructor fired".
Now when you say obj.calculateArea(); it will take the length and width that was set in the constructor
and calculate the area.
Above case can be useful when you want to allow people to create objects but if they dont give the
length and width you want these default values to be assigned using the constructor and calculate the
area.
21
Parametric constructor :
We can also have contructors that can accept some values as below:
22
SmallBox obj = new SmallBox();
obj.calculateArea();
//if i dont pass any value then it will call the default contructor without any arguments
//I want to call parametric constructor which requires length and width, for that you
have to pass values to the constructor like below:
SmallBox ups = new SmallBox(3, 4);
}
}
---------------------------------
when you give 3, 4, then 3 is passed to length and 4 is passed to width of the parametric constructor in
SmallBox class.
When ups calls calculateArea(), it will take 3 and 4 as length and width, and they are set as class level
data in the parametric constructor. Save and run the TestBox class.
--------------------------------
public class TestBox
{
public static void main(String[] args)
{
SmallBox obj = new SmallBox(); //this will set the length and width by calling
the default constructor
obj.calculateArea(); //this will calculate area using the default
constructor values
SmallBox ups = new SmallBox(3, 4); //this will set the length and width by calling
the parametric constructor
ups.calculateArea(); //this will calculate area using the values
passed in the parametric constructor
}
}
In C language, we can create class and objects but still C is not called as object oriented programming
language.
Whereas java and C++ area called OOP
23
For a language to be called an object oriented programming language, it has to satisfy 3 rules or
concepts:
1. Encapsulation
2. Polymorphism
3. Inheritence
Encapsulation :
-data hiding
Polymorphism :
-Overloading
-Overriding
Inheritence :
Abstract class
interface
24