Assignment Operator and "this" Keyword

Consider the following code snippet:

class Parent { Parent() { this = new Child(); } } class Child extends Parent { } 

The above will output a syntax error: The left hand side of an assignment operator must be a variable

In java, the this stores the memory address of the current caller. I want to overwrite the current object with an instance of a subclass of the class. I understand that the above snippet throws an error since this not a variable and probably unchanged.

However, I want to know why Java does not allow this function above? Are there any disadvantages?

EDIT . This question arose with me in the context of the Natural Language Processing (NLP) context. For example, in French, each verb must end with the words "er", "ir", or "re". All verbs have some common features. However, each verb must be either one of the three types mentioned above. Therefore, in the constructor of the parent class "Verb" I want to classify the object created as "ErVerb", "IrVerb" or "ReVerb".

+5
source share
2 answers

There are two scenarios:

If you give this instance an Object at all, not necessarily one in the type hierarchy, then the instance will not have any guarantees regarding the contents of its reference. This breaks a couple of things, primarily the whole concept of object-oriented programming.

If you restrict this to an instance of a subclass of the parent class, then this subclass constructor will call the parent constructor infinitely many times, raising a StackOverflowError .

+7
source

It does not make sense to create an instance of the subclass inside the parent constructor and replace the actual parent instance with the created child instance.

Despite the nasty StackOverflowError pointed out in the comments and in another answer, there is no case for this. In general, it is absurd (from a logical point of view) to create a child when creating a parent.

Consider the following considerations:

A specific car is assembled in a factory. The assembly process of a particular car consists of several stages.

Some of these steps occur only during the assembly of a particular vehicle, while others occur both during the assembly of a specific vehicle and in the assembly of other vehicles, such as a particular van.

Now, suppose that one of these general steps involved in assembling many vehicles (including both a specific vehicle and a specific van) indicates that we must assemble a new specific van and allow it to be assembled by a common vehicle.

Now the particular car we were assembling would become this new concrete van. But it is impossible for the car to be van => ABSURD .

+2
source

Source: https://habr.com/ru/post/1213076/


All Articles