Hi,
I am learning Java. I would like to know what is the significance of instantiating an object without an assignment.
I have created a class TestClass1 with a single constructor that prints a test message.
In TestClass2, if I write "new TestClass1()" rather than "TestClass1 x = new TestClass1()" it still works, and prints the test message.
I would like to know if I do not assign an object at the time of instantiation, it cannot be referenced or reused later, then what is the significance of this type of construct and when it can be useful, and where is the object being held.
public class TestClass1 {
TestClass1() {
System.out.println("This is a test message");
}
}
public class TestClass2 {
public static void main (String... args) {
TestClass1 x = new TestClass1(); //This prints "This is a test message"
new TestClass1(); //This also prints "This is a test message"
String y = new String("abc"); //this makes sense
//The following does not throw an exception - what purpose could this conceivably serve
new String("def");
}
}