Is there a way to override class variables in Java?

后端 未结 17 1059
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 09:49
class Dad
{
    protected static String me = \"dad\";

    public void printMe()
    {
        System.out.println(me);
    }
}

class Son extends Dad
{
    protected         


        
17条回答
  •  无人及你
    2020-11-22 10:27

    If you are going to override it I don't see a valid reason to keep this static. I would suggest the use of abstraction (see example code). :

         public interface Person {
            public abstract String getName();
           //this will be different for each person, so no need to make it concrete
            public abstract void setName(String name);
        }
    

    Now we can add the Dad:

    public class Dad implements Person {
    
        private String name;
    
        public Dad(String name) {
            setName(name);
        }
    
        @Override
        public final String getName() {
        return name;
        }
    
        @Override
        public final void setName(String name) {
            this.name = name;
        }
    }
    

    the son:

    public class Son implements Person {
    
        private String name;
    
        public Son(String name) {
            setName(name);
        }
    
        @Override
        public final String getName() {
            return name;
        }
    
        @Override
        public final void setName(String name) {
            this.name = name;
        }
    }
    

    and Dad met a nice lady:

    public class StepMom implements Person {
    
        private String name;
    
        public StepMom(String name) {
            setName(name);
        }
    
        @Override
        public final String getName() {
            return name;
        }
    
        @Override
        public final void setName(String name) {
            this.name = name;
        }
    }
    

    Looks like we have a family, lets tell the world their names:

    public class ConsoleGUI {
    
        public static void main(String[] args) {
            List family = new ArrayList();
            family.add(new Son("Tommy"));
            family.add(new StepMom("Nancy"));
            family.add(new Dad("Dad"));
            for (Person person : family) {
                //using the getName vs printName lets the caller, in this case the
                //ConsoleGUI determine versus being forced to output through the console. 
                System.out.print(person.getName() + " ");
                System.err.print(person.getName() + " ");
                JOptionPane.showMessageDialog(null, person.getName());
        }
    }
    

    }

    System.out Output : Tommy Nancy Dad
    System.err is the same as above(just has red font)
    JOption Output:
    Tommy then
    Nancy then
    Dad

提交回复
热议问题