Override member data in subclass, use in superclass implementation?

前端 未结 3 1206
广开言路
广开言路 2021-02-10 14:22

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

    This way you are hiding the parent variable stuff with the defined stuff.

    Try giving value to stuff in the initialization block (or in the constructor):

    abstract public class BasicStuff {
      protected String[] stuff;
    
      {
        stuff = new String[] { "Pizza", "Shoes" };
      }
    
      public void readStuff() {
        for(String p : stuff) { 
          System.out.println(p); 
        }
      }
    }
    

    ..

    public class HardStuff extends BasicStuff {
      {
        stuff = new String[] { "Harmonica", "Saxophone", "Particle Accelerator" };
      }
    }
    

提交回复
热议问题