I've seen places where object creation factories are implemented by having a reference to the class object and having a create
method which does this:class.newInstance()
, which uses reflection, and might not be efficient compared to calling the default constructor directly.
If java supported something like return new this();
, I could implement this in a parent class and that would work as a factory method (and would throw an exception if there is no such constructor as does class.newInstance()
).
Why isn't such a thing supported?
PS: My first question in stackOverflow :)
Output. The "this" keyword is used as a reference to an instance. Since the static methods doesn't have (belong to) any instance you cannot use the "this" reference within a static method.
Static methods can't access instance methods and instance variables directly. They must use reference to object. And static method can't use this keyword as there is no instance for 'this' to refer to.
"this" keyword is only applicable where an instance of an object is created. And in static method no instance is created because static method belongs to class area.
The correct answer to the question “What is not the use of 'this' keyword in Java” is, option (d). Passing itself to the method of the same class. This is one of the most important keywords in Java and is used to distinguish between local variables and variables that are passed in the methods as parameters.
As designed, the this
keyword is valid only in the context of an instance. Its type is the type of the class within which it occurs.
From the Java Language Specification:
When used as a primary expression, the keyword this denotes a value that is a reference to the object for which the instance method was invoked (§15.12), or to the object being constructed.
If you want to create a new object using the default constructor, you can call it directly.
return new MyType();
If you want to create a clone of an object, you may be able to use the Object.clone()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With