Why are Java fields not polymorphic?

I was looking at this answer and I don't understand the logic why the methods would be polymorphic but not fields.

All member functions are polymorphic in Java by default. This means when you call this.toString () Java uses dynamic binding to resolve the call, the call to the child version. When you access member x, you are accessing the member of your current scope (father), since members are not polymorphic.

When you have a field x

in super and subclass and overrides toString

in your subclass when you call the following in the base class:

System.out.println(this); //calls the subclass toString implementation
System.out.println(this.x) //prints the base class x field

      

The rationale behind this in the answers listed in the question linked at the beginning is that the base class doesn't "know" about the subclass when it's in its scope, but with polymorphism, it's the same thing: the superclass doesn't know which subclass exists, but the subclass method is still called. So, what exactly does Java do that does two things differently, one uses dynamic binding in the subclass and one maintains the scope of the superclass?

Edit: To clarify, I am stuck on why this.x will do the same as polymorphism, look at the actual type of the object, not just the reference type, and print the field x

from the subclass.

+3


source to share


1 answer


To achieve Java subtype politism, you need to keep track of which method to invoke, which requires additional overhead. You can get "polymorphic fields" by keeping the fields private and using getters (the former is not required, but smart to do). You may be interested in checking

  • invokedynamic
  • invokeinterface
  • invokespecial
  • invokestatic
  • invokevirtual


challenges. You can read more about it here: https://docs.oracle.com/javase/specs/jvms/se8/html/jvms-6.html#jvms-6.5.invokevirtual

+1


source







All Articles