Call a child class method from a parent class object

后端 未结 7 529
星月不相逢
星月不相逢 2020-12-06 09:35

I have the following classes

class Person {
    private String name;
    void getName(){...}}

class Student extends Person{
    String class;
    void getCl         


        
7条回答
  •  有刺的猬
    2020-12-06 10:36

    Many of the answers here are suggesting implementing variant types using "Classical Object-Oriented Decomposition". That is, anything which might be needed on one of the variants has to be declared at the base of the hierarchy. I submit that this is a type-safe, but often very bad, approach. You either end up exposing all internal properties of all the different variants (most of which are "invalid" for each particular variant) or you end up cluttering the API of the hierarchy with tons of procedural methods (which means you have to recompile every time a new procedure is dreamed up).

    I hesitate to do this, but here is a shameless plug for a blog post I wrote that outlines about 8 ways to do variant types in Java. They all suck, because Java sucks at variant types. So far the only JVM language that gets it right is Scala.

    http://jazzjuice.blogspot.com/2010/10/6-things-i-hate-about-java-or-scala-is.html

    The Scala creators actually wrote a paper about three of the eight ways. If I can track it down, I'll update this answer with a link.

    UPDATE: found it here.

提交回复
热议问题