Why aren't Java fields polymorphic?

前端 未结 1 769
情书的邮戳
情书的邮戳 2021-01-20 10:02

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

All member functions are polymorp

1条回答
  •  说谎
    说谎 (楼主)
    2021-01-20 10:34

    To achieve subtype polymorphism Java needs to keep track of which method to call, it requires additional overhead. You could achieve kind of "polymorphic fields" by keeping fields private and using getters (the former is not required, but sensible to do). You may be interested in checking out

    • invokedynamic
    • invokeinterface
    • invokespecial
    • invokestatic
    • invokevirtual

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

    0 讨论(0)
提交回复
热议问题