Computer Applications

What are the temporary instances of a class?

Java Constructors

16 Likes

Answer

If we don't assign an object created by the new operator to a variable then it is known as a temporary instance or an anonymous object. If we want to use an object only once, then we can use it as a temporary instance. The below example illustrates this:

class Sum {
    int x;
    int y;

    public Sum(int a, int b) {
        x = a;
        y = b;
    }

    public void computeSum() {
        int s = x + y;
        System.out.println("Sum = " + s);
    } 

    public static void main(String[] args) {
        new Sum(3, 5).computeSum();
    }
}

In the main method, the object of class Sum is not assigned to any variable. We use it just to print the sum of 3 and 5 after which it is destroyed.

Answered By

7 Likes


Related Questions