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