zoukankan      html  css  js  c++  java
  • Java基础-重写-子类重写父类中的方法后执行情况

    代码

    public class Test {
        public static void main(String[] args)  {
            Shape shape = new Circle();
            System.out.println(shape.name);
            shape.printType();
            shape.printName();
        }
    }
     
    class Shape {
        public String name = "shape";
         
        public Shape(){
            System.out.println("shape constructor");
        }
         
        public void printType() {
            System.out.println("this is shape");
        }
         
        public static void printName() {
            System.out.println("shape");
        }
    }
     
    class Circle extends Shape {
        public String name = "circle";
         
        public Circle() {
            System.out.println("circle constructor");
        }
         
        public void printType() {
            System.out.println("this is circle");
        }
         
        public static void printName() {
            System.out.println("circle");
        }
    }

    结果

    shape constructor
    circle constructor
    shape
    this is circle
    shape

    这道题主要考察了隐藏和覆盖的区别(当然也和多态相关)

     覆盖只针对非静态方法(终态方法不能被继承,所以就存在覆盖一说了),而隐藏是针对成员变量和静态方法的。这2者之间的区别是:覆盖受RTTI(Runtime type  identification)约束的,而隐藏却不受该约束。也就是说只有覆盖方法才会进行动态绑定,而隐藏是不会发生动态绑定的。在Java中,除了static方法和final方法,其他所有的方法都是动态绑定。因此,就会出现上面的输出结果。

  • 相关阅读:
    Nginx从安装到配置文件详解
    python流程控制语句
    python数据类型以及方法
    python介绍以及基础基础语法
    new 操作符
    js 模拟substr
    js 对于链式加载的思考
    js 实现哈夫曼树
    js实现深度优先
    js 广度优先遍历
  • 原文地址:https://www.cnblogs.com/hwaggLee/p/4491330.html
Copyright © 2011-2022 走看看