Override member data in subclass, use in superclass implementation?

前端 未结 3 976
醉梦人生
醉梦人生 2021-02-10 14:36

In Java, is it possible to override member data in a subclass and have that overridden version be the data used in a super class\'s implementation?

In other words, here\

3条回答
  •  醉酒成梦
    2021-02-10 15:03

    I believe you must interpose an accessor method, i.e., use:

        for(String p : getStuff()) { 
    

    in the superclass, and add:

        protected String[] getStuff() { return stuff; }
    

    wherever you have a protected String[] stuff redefinition.

    Overriding really applies to methods, not data (at least, that is so in the Java model; some other languages do things differently), and so to get the override effect you must interpose a method (typically a dirt-simple accessor, like here). It doesn't really complicate things at all, it's just a very simple way to instruct the Java compiler to use, intrinsically, the "extra level of indirection" that your desired behavior requires.

提交回复
热议问题