Reputation: 363
Consider the following code snippet:
class Parent {
Parent() {
this = new Child();
}
}
class Child extends Parent { }
The above would throw a syntax error: The left hand side of an assignment operator must be a variable
In java, the this
keyword stores the memory address of the current calling object. I wish to overwrite the current object with an instance of the class' subclass. I understand the above snippet is throwing an error as this
is not a variable and is probably immutable.
However, I wish to know why java doesn't allow this above feature? Is there any downside to it?
EDIT: This question occurred to me with reference to a Natural Language Processing (NLP) context. For example, in the French language, every verb has to end with 'er', 'ir' or 're'. All verbs have certain features in common. However, every verb must be either one of the three types mentioned above. So in the constructor of the parent class 'Verb', I want to categorize the object created as an 'ErVerb', 'IrVerb' or 'ReVerb'.
Upvotes: 5
Views: 210
Reputation: 34460
It doesn't make any sense to construct a subclass instance inside the parent's constructor and substitute the actual parent instance with the created child instance.
Despite the nasty StackOverflowError
pointed out in the comments and in the other answer, there's no use case for doing this. In general, it's absurd (from the logical point of view) to create a child while creating the parent.
Consider the following reasoning:
A specific car is being assembled in a factory. The process to assemble a specific car consists of many steps.
Some of these steps only occur when assembling the specific car, while others occur both when assembling the specific car and when assembling other vehicles, such as a specific van.
Now let's suppose that one of these general steps that occur when assembling many vehicles (including both the specific car and the specific van), indicates that we must assemble a new specific van and let it be the general vehicle being assembled.
Now, the specific car we were assembling would have become this new specific van. But it's impossible for a car to be a van => ABSURD.
Upvotes: 2
Reputation: 10810
There are two scenarios:
If you let this
be instantiated to any Object
whatsoever, not necessarily one in the type hierarchy, then an instantiation would have no guarantee about the contents of its reference. This breaks a couple things, most notably the entire concept of object-oriented programming.
If you restrict this
to be instantiated to any subclass of the parent class, then that subclass constructor would call the parent constructor infinitely many times, causing a StackOverflowError
.
Upvotes: 7