Java abstract class fields override

后端 未结 6 949
春和景丽
春和景丽 2020-12-06 11:34

I have an abstract class that should implement a public field, this field is an interface or another abstract classe.

something like this:

public abstr         


        
6条回答
  •  余生分开走
    2020-12-06 12:03

    Why nobody is observing that program will throw NullPointerException.
    subclass's field with same name will hide super class's field. There is no overriding with field. Overriding is only possible with methods.

    Original Code by Author:

    public abstract class GenericContainer {
        public GenericChild child;
    }
    
    public abstract class GenericChild {
        public int prop1=1;
    }
    
    public abstract class SpecialChild extend GenericChild {
        public int prop1=2;
    }
    
    public abstract class SpecialContainer extends GenericContainer {
        public SpecialChild child=new SpecialChild(); //PAY ATTENTION HERE!
    }
    
    public class ExternalClass {
        public GenericContainer container=new SpecialContainer();
        public int test() {
             return container.child.prop1
        }
    }
    

提交回复
热议问题