Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we create an object with the "this" keyword in java? [closed]

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 :)

like image 782
radiantRazor Avatar asked May 24 '13 13:05

radiantRazor


People also ask

Why we Cannot use this keyword in static block in Java?

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.

What kind of class methods Cannot use the this keyword?

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.

Why this keyword is non static?

"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.

What is not the use of this keyword in Java?

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.


1 Answers

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.

like image 134
Andy Thomas Avatar answered Sep 20 '22 15:09

Andy Thomas