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方法,其他所有的方法都是动态绑定。因此,就会出现上面的输出结果。

  • 相关阅读:
    使用闭包的注意点
    JS中的回收机制
    jQuery选择器之样式
    PNRPC 2017-2018 Gym101615I
    Verilog碎碎念
    Codeforces 420D. Cup Trick
    AGC017C. Snuke and Spells
    XVII Open Cup named after E.V. Pankratiev. GP of Tatarstan B. White Triangle
    SPOJ TETRIS2D
    AGC017B. Moderate Differences
  • 原文地址:https://www.cnblogs.com/hwaggLee/p/4491330.html
Copyright © 2011-2022 走看看