Let's start
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 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 variable are sufficient(height, width and area)
⇒Declare 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 class and rec1 is the name of 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();
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 */
0 Comments