I have two classes :
import android.cla;
public class CW {
public static void main(String [] args){
System.out.println(new cla());
}
}
public class Cl {
@Override
public String toString(){
return "LOL";
}
}
In the first class I’m calling the objects toString() method, which has been overriden and printing it to console. It clearly returns “LOL”;
I have two questions :
-
Is it possible to return data while instantiating like this (
new cla()) without overriding the objectstoString()method; and -
What is the proper term for instantiating classes like this (
new cla()), that’s without declaration like :Object l = new cla()
Thanks. Please correct me on the proper terms.
1 – No it isn’t. A ‘constructor’ is a special method on the class that always returns an object instance of the class. The whole point of the constructor is to return the object. So no, it can’t return anything else.
1a – The reason that
System.out.printlncalls thetoStringmethod is because you are asking it to print out that object to the screen, and thetoStringmethod is the method chosen by the authors ofprintln(and the Java language in general) to give a string representation of the object.2 – That way of writing isn’t really called anything. It’s just an expression that you’re passing as an ‘actual parameter’ to the
printlnmethod. True, it’s an expression that instantiates a new object, but it’s no different toprintln("a string"). You could call it an anonymous object if you really wanted to.2a – (old answer that doesn’t actually answer your question but I’ll keep it here) That’s just called ‘using a less derived reference† to a class’. Beware you can only call methods on the type of the reference, so if you added extra methods to your
Clclass you couldn’t call them from anObjectreference. Look into Liskov substitution principle.† ‘less derived’ or ‘supertype’ or ‘superclass’ or ‘more general class’ etc…