Translate

Class and Object in Java.

Object

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 class.
3.Member functions are the function used inside class.
4.It is also called Userdefined data type.

 Syntax of class

Example

Importent point to remember while making class program
⇒Declare variable with appropriate data type as per your requirement
for example to find the area of recatngle three variable are sufficient(height, width and area)
⇒Declare function as per your requirement
for example to find the area of recatngle 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 class and rec1 is the name of object.
⇒Accessing data member and member fucntion
Data member and member fucntion of a class can be accessed using Dot(.) operator.
⇒Accessing data member
rec1.height;
⇒Accessing member function
rec1.findArea();

class Rectangle
{
//Data Member 
int height;
int width;
int area;
//Member function
void findArea()
 {
  area=height*width;
  System.out.println("Area of Rectangle="+area);
 }
 public static void main(String[] args) 
 {
  //creating object
  Rectangle obj=new Rectangle();
  //accessing data member
  obj.height=25;
  obj.width=15;
  //accessing member function
  obj.findArea();
 }
}
/*
### Output ###
Area of Rectangle=375
*/

Example 2

class Rectangle
{
//Data Member 
int height;
int width;
int area;
//Member function
void getPara()
{
  height=15;
  width=25;
}
//Member function
void findArea()
 {
  area=height*width;
  System.out.println("Area of Rectangle="+area);
 }
 public static void main(String[] args) 
 {
  //creating object
  Rectangle obj=new Rectangle();
  //accessing member function
  obj.getPara();
  obj.findArea();
 }
}
/*
### Output ###
Area of Rectangle=375
*/
Next Post Previous Post
No Comment
Add Comment
comment url