Answer the question
In order to leave comments, you need to log in
Why is inheritance implemented this way in Java?
Good day to all,
I recently wrote a project in Java. At the same time, the behavior of the methods of the parent classes was somewhat surprising.
Quote from Wiki:
Virtual method (virtual function) - in object-oriented programming, a method (function) of a class that can be overridden in descendant classes so that the specific implementation of the method to be called will be determined at runtime. Thus, the programmer does not need to know the exact type of an object in order to work with it through virtual methods: it is enough to know that the object belongs to the class or descendant of the class in which the method is declared. One of the translations of the word virtual from English can be "actual", which is more appropriate in meaning.
Virtual methods are one of the most important techniques for implementing polymorphism. They allow you to create common code that can work both with objects of the base class and with objects of any of its descendant classes. In this case, the base class defines a way to work with objects, and any of its heirs can provide a concrete implementation of this way.
public class A {
...
public String getType() {
return this.type;
}
private String type = "null";
}
public class B {
...
private String type = "type_B";
}
Answer the question
In order to leave comments, you need to log in
You cannot override field values, as it works with methods. In your example, you simply defined a new field with the same name, resulting in something called name shadowing .
If you are trying to implement reflection, it is better to use standard tools.
If you want to set the value of the parent field in the child , make a constructor in the parent with the appropriate parameter.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question