Objects and Classes in Java

Objects in Java:

In Java, objects are 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;
t1=new Test();

The 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.

Classes in Java:

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
{
int l, w;
void getdata(int x, int y)
{
l=x;
w=y;
}
int homearea()
{
int area=l*w;
return(area);
}
}
class Test
{
public static void main(string arg[])
{
int a1, a2;
Home h1=new Home();
Home h2=new Home();
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 the before a program, each containing its own set of variables, we should assign values to these variables 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, the 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 the second case, the method getdata can be used to call Home objects to set all values of l and w.

Home h2=new Home();
h2.getdata(15,20);