美文网首页
记一次由继承、重写和重载引发的事故

记一次由继承、重写和重载引发的事故

作者: 天地一蜉蝣_6e86 | 来源:发表于2019-06-21 14:09 被阅读0次

    在同时使用继承、重写和重载时,java 的调用链就会变得异常复杂,所以对这部分不了解的同学请谨慎使用

    以下是示例代码:

    public class Father {

    protected void print(List<String> msg)

    {

    msg.add("father said somthing");

    msg.stream().forEach(m->System.out.println(m));

    }

    protected void print(Listmsg<String> word){

    msg.add("father yowl "+word);

    this.print(msg);

    }

    protected void print(List<String> msg ,String word,String way)

    {

    msg.add("father "+way +" "+word);

    this.print(msg);

    }

    }

    public class Son extends Father {

    @Override

        protected void print(List<String> msg)

    {

    msg.add("son said something");

    super.print(msg);

    }

    @Override

        protected void print(List<String> msg,String word){

    msg.add("son yowl "+word);

    super.print(msg,word);

    }

    public static void main(String[]args) {

    Son son =new Son();

    son.print(new ArrayList(),"hello world","speak");

    }

    }

    打印结果:

    father speak hello world

    son said something

    father said somthing

    在father 中定义的print(List<String> msg,String word,String way) 本意是调用father中的 print(List<String> msg),但是由于son 重写函数,导致通过 this 调用到son 的print(List<String> msg)

    所以在继承和重写的时候要注意this 调用的是父还是子的函数。上面的写法会给其他开发者一个错觉。类似上述代码中的father 中的print(List<String> msg) 作为一个必要动作,也就是father 的子类想要执行print 动作,最终都要执行的动作,就需要将这个函数独立出来,用final 修饰,不允许重写,以免引起误解。

    相关文章

      网友评论

          本文标题:记一次由继承、重写和重载引发的事故

          本文链接:https://www.haomeiwen.com/subject/jjqyqctx.html