0% found this document useful (0 votes)
10 views

Java Notes 4 (Class and Object)

Java

Uploaded by

riteshawachat5
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Java Notes 4 (Class and Object)

Java

Uploaded by

riteshawachat5
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

 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:

input salary, bonus;


totalPay = salary + bonus;
print totalPay;

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.

 In OOPs there is something called as Class :

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;
}

Now if you remember, this syntax is very similar to this: int x, y, z;

So just like int x,y,z; we also have Employee akshay, laxmi , ritesh;

When you say int x,y,z that means


x can hold an integer,
y can hold an integer,
z can hold an integer

i.e, you can assign some integer to x,y,z.

Same way when you say Employee akshay, laxmi, ritesh, that means,

akshay can hold an Employee


laxmi can hold an Employee
ritesh can hold an Employee

just like x, y, z hold an integer.

2
 So what does it mean by holding an Employee?

Now when you say int x, i.e. x can hold an integer,


and when you say akshay can hold an employee, it means
akshay will have his own salary , own bonus and his own calculateTotalPay() method.

 That means we can say 

Since employee has a salary, akshay will also have a salary


akshay.salary = 90000;

Since employee has a bonus, akshay will also have a bonus


akshay.bonus = 20000;

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

So akshay, laxmi and ritesh are what you call as OBJECTS.

3
 So what is an object ?
An object can be defined as a copy of a class.

if you notice, akshay is nothing but a copy of class Employee


Since Employee has salary, bonus ; akshay will also have salary and bonus and akshay will have it's own
copy of calculateTotalPay()

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.

 So how we define object?

Object is a copy of a class. Some people also call object as an instance of a class.

 So in this case, what is a class ?


A class is a template for an object.
Meaning of template- if you use MS word document, you can create new documents from an existing
template. And then you can type your own letter.

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.

So a class is nothing but a template for an object.

 So what a class usually contains?

class Employee
{
//This is called as data
double salary;
double bonus;

//This is called as method


CalculateTotalPay()
{
totalPay = salary + bonus;
print totalPay
}
}

So a class usually contains data and methods.

4
Class can have multiple data and multiple methods.

 Now lets take Another Example :

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.

So lets actually implement both of the above examples in eclipse :


Create a package named classAndObjects
create a class Employee, do NOT select the checkbox - public static void main

we will have salary bonus and calculateTotalPay method in this class:


------------------------------
package classAndObjects;
public class Employee
{
double salary;
double bonus;

//This method will throw an error


calculateTotalPay()
{
double totalPay = salary + bonus;

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;

//void added as a return type since its not returning anything


void calculateTotalPay()
{
double totalPay = salary + bonus;
System.out.println("Total Pay:" + totalPay);
}
}
---------------------------------
Now lets create another class in the same package. Name it as TestEmployee
also select the public static void main checkbox
---------------------------------
package classAndObjects;
public class TestEmployee
{

public static void main(String[] args)


{

}
}
---------------------------------
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

we can also create objects like below:

Employee akshay = new Employee();


Employee laxmi = new Employee();
Employee ritesh = new Employee();

this new akshay(); is required, you are initializing the object.

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.

you can say :


akshay.(dot) and here you will see salary,bonus and calculateTotalPay() in the auto suggestion window,

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()

when you say akshay.(dot) ; these things must come


Now save the code and run this TestEmployee class.
-------------------------------------------
package classAndObjects;
public class TestEmployee
{
public static void main(String[] args)
{
/*Employee akshay, laxmi, ritesh;
akshay = new Employee();
laxmi = new Employee();
ritesh = new Employee();*/

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();*/

Employee akshay = new Employee();


Employee laxmi = new Employee();
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.

save the TestBox class and run it


-----------------------------

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.

2.data (variable name)


Data always starts with a lower case. If you have one word then that word should be in lower case. If yu
have more than one word then follow camel case.

 Example :

int abc;
String myName;
int primeNumber;
char yourGrade;
int yourPassingMarks;

11
3. Method name: same as data (variable) names
 Example :

add();
addNumbers();
calculateTotalPay();

 Method returning a value:

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;
}

So when you return this area, we want to catch hold of it somewhere,


So in the main method we have to declare something like below:

//ups.calculateArea();// instead of directly calling the method, we need to assign this method to an
integer variable

int area1 = ups.calculateArea();

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.

int area2 = ups.calculateArea();

Now we have access to area1 and area2 in the main method so we can write:

sysout("Total area of ups and fedEx = " + (area1 + area2));


----------------------------------------------------

 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();

sysout("Total area of ups and fedEx = " + (area1 + area2));


}
}

 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)
{

Box ups = new Box();


Box fedEx = new Box();

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.

Similarly in case of fedEx -->fedEx.calculateArea(2)

This way you can pass values to a method.


This integer x is called as passing arguments.

Now some times, you will see something like below in the box class:

int calculateArea(int length, int breadth)


{
int area = length * breadth * x;
System.out.println("Area: " + area);
return area;
}

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

sysout("Total area of ups and fedEx = " + (area1 + area2));


}
}
------------------------------
Now if you notice, we have passed values while calling the calculateArea method in the TestBox class
and then

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()

int calculateArea(int length, int breadth)


{
int area = length * breadth;
System.out.println("Area: " + area);
return area;
}

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

ups.length = 5;//class level data


ups.breadth = 10;//class level data
int area1 = ups.calculateArea(4, 3); //data as a passing arguments

Using "this" keyword:


we can use the class level data and ignore local data by using keyword "this":

int calculateArea(int length, int breadth)


{

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.

 Run the program(run TestBox class) :

----------------------------------------------------
//Box class :

package classAndObjects;
public class Box
{
int length; //class level data
int breadth; //class level data

int calculateArea(int length, int breadth)


{
int area = this.length * this.breadth; //this will point to class level data and
ignore the arguments passed.
System.out.println("Area: " + area);
return area;
}
}
-----------------------
//TestBox class :

package classAndObjects;
public class TestBox
{
public static void main(String[] args)
{
Box ups = new Box();
Box fedEx = new Box();

ups.length = 5; //this data will be considered


ups.breadth = 10; //this data will be considered

18
int area1 = ups.calculateArea(4,3); //this will be ignored

fedEx.length = 6; //this data will be considered


fedEx.breadth = 7; //this data will be considered
int area2 = fedEx.calculateArea(2,5); //this will be ignored

sysout("Total area of ups and fedEx = " + (area1 + area2));


}
}

 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.

If that is a case we can use something called as Constructor.

 So what is a constructor :

It is a method that has the same name as class.


It is executed when an object is created.
It is used to set default values.
it does not return anything including void, so no data type is passed with this method like void , int, etc.

Lets create a method same as class name:


------------------------
public class SmallBox
{
int length;
int width;
//constructor -- same name as class and no return type
SmallBox()
{
this.length = 5;
this.width = 6;
System.out.println("Constructor fired")
}

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:

SmallBox(int length, int width)


{
this.length = length; //setting the class level length using passing arguments in
constructor
this.width = width: //setting the class level width using passing arguments in
constructor
}
---------------------------
public class SmallBox
{
int length;
int width;
//default constructor -- same name as class
SmallBox()
{
this.length = 5;
this.width = 6;
System.out.println("Constructor fired")
}
//Parametric constructor -- same name as class with passing arguments
SmallBox(int length, int width)
{
this.length = length;
this.width = width;
}
void calculateArea()
{
System.out.println("Area = " + (length * width));
}
}
------------------------------
Now to call the parametric constructor we can create another object of SmallBox class in the main
method as below:
------------------------------
public class TestBox
{
public static void main(String[] args)
{

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
}
}

 Object Oriented programming(OOPs) :


lets see what makes a language an object oriented programming language.

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

So what makes a langauge to be called an object oriented programming language.

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

C langauge supports encapsulation and polymorphism but it doesn't supports inheritance.


Java/C++ supports all of the above 3 concepts that is the reason they are called OOP language

In OOPS for java we will see below sections in details:

 Encapsulation :

-data hiding

 Polymorphism :

-Overloading
-Overriding

 Inheritence :

Abstract class
interface

24

You might also like