Classes are blueprint of any real entity in Java. A class contains of two types of members; a data or variable and another is method or function.

Variable defined within a class are called as instance variables because each instance of the class (object of class) contains its own copy of these variables. Thus data of one object doesn’t affect the others.

The General form of a class:

class <name of class>{

// variables

<data type> <instance variable1>;

<data type> <instance variable2>;

                //methods

                <data type> <method name1(parameters)>{

//body of the method

}

<data type> <method name2(parameters)>{

//body of method

}

}//end of class

 

Example: Simple class

class Box{

           //variables of the class

      int height;

      int width;

      int depth;

}

 Object creation of box class:

Box obj = new Box();

Box obj1=new Box();

Note:
  • As mentioned earlier,each object of a class is created, it contains its own copy of each instance variable defined by the class.
  • Thus, every object of box class contain its own copy of instance (object) variables that are height, width, depth.
  • To access  these variable, you will use the dot(.) operator. The dot operator links the name of the object with name of variable.

For example: obj.width = 100; // variable initialization of object obj

obj1.width = 500; // variable initialization of object obj1

  • both variable are differ from the other.

class Box{

int height;

int width;

int depth;

}

class BoxEntity{

public static void main(String arg[]){

//creating object of box class

Box boxObj = new Box(); //object

//assigning value to the variable of instance

boxObj.height=20;

boxObj.width=30;

boxObj.depth=40;

// compute volume of box

int vol = boxObj.width * boxObj.height * boxObj.depth;

Syste.out.println(“volume of box is”+vol);

}

}

Hope you have learned something new today, keep Learning. Please do check out my blog on What is and how to use the Constructors in JAVA?

Leave a Reply

Your email address will not be published. Required fields are marked *