Java-Declaring Objects

Declaring Objects

An object is an instance of a class. The relationship is such that many objects can be created using one class. Each object has its own data but its underlying structure are defined by the class. There are two steps when creating an object from a class :

Declaration A variable declaration with a variable name with an object type.
Initialization The new key word is used to create the object.

Example of creating an object is given below :

The first line declares a2 as a reference to an object of type Area. After this line executes, A2 contains the value null, which indicates that it does not yet point to an actual object. Any attempt to use a2 at this point will result in a compile-time error. The next line allocates an actual object and assigns a reference to it to a2. After the second line executes, you can use a2 as if it were a area object. But in reality, a2 simply holds the memory address of the actual Area object.


Program Source

class Area{
    int length;
    int hight;
    int width;

public class Javaapp {

    public static void main(String[] args) {
        Area a1 = new Area();
        Area a2;
        a2 = new Area();

Leave a Comment