Object :
The object is having states and behaviors in which state means what does it has and behavior means what does it do. for example, a pen has
States: ink,nib,needle,cap etc
Behaviors: Writing.
Class :
1. It is a collection of data members and member functions.
2. Data members are the variable used inside the class.
3. Member functions are the function used inside the class.
4. It is also called a User-defined data type.
Syntax of Class :
Example:
Important point to remember while making class program
⇒Declare variable with appropriate data type as per your requirement
for example to find the area of rectangle three variables are sufficient(height, width and area)
⇒Declare the function as per your requirement
for example, to find the area of rectangle single function findArea() is sufficient.
⇒Create instance(object) of class to access the data member and member function of a class.
classname objectname;
Example:- Rectangle rec1;
Here Rectangle is the name of the class and rec1 is the name of the object.
⇒Accessing data member and member function
Data member and member function of a class can be accessed using Dot(.) operator.
⇒Accessing data member
rec1.height;
⇒Accessing member function
rec1.findArea();
Program 1:
1: class Rectangle
2: {
3: //Data Member
4: int height;
5: int width;
6: int area;
7: //Member function
8: void findArea()
9: {
10: area=height*width;
11: System.out.println("Area of Rectangle="+area);
12: }
13: public static void main(String[] args)
14: {
15: //creating object
16: Rectangle obj=new Rectangle();
17: //accessing data member
18: obj.height=25;
19: obj.width=15;
20: //accessing member function
21: obj.findArea();
22: }
23: }
24: /*
25: ### Output ###
26: Area of Rectangle=375
27: */
Program 2:
1: class Rectangle
2: {
3: //Data Member
4: int height;
5: int width;
6: int area;
7: //Member function
8: void getPara()
9: {
10: height=15;
11: width=25;
12: }
13: //Member function
14: void findArea()
15: {
16: area=height*width;
17: System.out.println("Area of Rectangle="+area);
18: }
19: public static void main(String[] args)
20: {
21: //creating object
22: Rectangle obj=new Rectangle();
23: //accessing member function
24: obj.getPara();
25: obj.findArea();
26: }
27: }
28: /*
29: ### Output ###
30: Area of Rectangle=375
31: */