Objects and Classes in Java

Object : In Java, an object is essentially a block of memory that contains space to store all the instance variables.

Creating Objects : Creating an object is also referred to as instantiating an object.
In java, objects are created by using the new operator. The new operator creates an object of the specified class and returns a reference to that object.

Test t1;  // declare the object
t1=new Test(); // instantiate the object

First statement declares a variable to hold the object reference and the second statement assigns the object reference to the variable. The variable t1 is now an object of the Test class.

Class : A class is a user-defined data type with a template that serves to define its properties. A class is essentially a description of how to make an object that contains fields and methods.

Creating class :

class classname                      
{
   field declaration;
   methods declaration;
}

Application of classes and objects :
class Home                          // Declaration of class
{
 int l, w;
void getdata(int x, int y)
{
 l=x;
 w=y;
}
int homearea()
{
 int area=l*w;
return(area);
}
}
class Test                           // Declaration of class with main method 
{
public static void main(string arg[])
{
int a1, a2;
Home h1=new Home();                  // creating 1st object
Home h2=new Home();                  // creating 2nd object
h1.l=25;
h1.w=20;
a1=h1.l+h1.w;
h2.getdata(15,20);
a2=h2.homearea()
System.out.println("Area1 is ="+a1);
System.out.println("Area2 is ="+a2);
}
}

Output :
Area1 is = 500
Area2 is = 300

Accessing Class Members : Now we have created objects in before program, each containing its own set of variables, we should assign values to these variables in order to use them in our program. all variables must be assigned values before they are used. We are outside the class, we cannot access the instance variables and the methods directly. To do this, we must use the concerned object and the dot operator(.)

object-name.variablename=value;
object-name.methodname=(parameter-list);

Here object-name is the name of the object, variable-name is the name of the instance variable inside the object that we want to access, method name is the method that we want to call and parameter-list is a comma-separated list of actual values that must match in type and number with the parameter list of the method name declared in the class.
The instance variables of the Home class may be accessed and assigned values are given as follows :
h1.l=25;
h1.w=20;
h2.l=15;
h2.w=20;

In second case, the method getdata can be used to call Home objects to set all values of l and w.
Home h2=new Home();  // creating an object
h2.getdata(15,20);   // calling the method using the object