Java 重载与覆盖

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chennai1101/article/details/84287021

1. 重载与覆盖

  • 重载,提供多个具有相同名字的方法,但是它们具有可以彼此分开的不同签名。
  • 覆盖,将方法的超类实现替代为自己的实现,签名必须相同。
    • 如果返回的类型是引用类型,那么覆盖方法的返回类型可以申明为超类方法返回类型的值类型。
    • 子类可以改变超类方法的访问修饰符,但只能提供更多的访问权限。
    • 覆盖方法可以改变其他的方法修饰符,可以改变synchronizednativestrictfp修饰符。
    • 覆盖方法的throws必须少于超类方法的列出的throws类别。

2. 字段的覆盖

字段不可以被覆盖,只可以被隐藏。

  • 当通过方法引用字段时,取决于字段的可访问性。
  • 当通过对象引用时,由对象实际对应的类来决定。

例如在Sup和sub中都有一个变量value和静态变量staticValue,并且通过getValuegetStaticValue访问。静态成员由实际对应的类来决定。

public class Sup {
    public int value = 1;
    public static int staticValue = 10;

    public int getValue() {
        return value;
    }

    public static int getStaticValue() {
        return staticValue;
    }

}

public class Sub extends Sup {
    public int value = 2;
    public static int staticValue = 20;

    @Override
    public int getValue() {
        return value;
    }

    public static int getStaticValue() {
        return staticValue;
    }

    public static void main(String[] args) {
        Sup sup = new Sub();
        Sub sub = new Sub();

        System.out.println("sup.value = " + sup.value);
        System.out.println("sup.staticValue = " + sup.staticValue);
        System.out.println("sup.getValue() = " + sup.getValue());
        System.out.println("sup.getStaticValue() = " + sup.getStaticValue());

        System.out.println("sub.value = " + sub.value);
        System.out.println("sub.staticValue = " + sub.staticValue);
        System.out.println("sub.getValue() = " + sub.getValue());
        System.out.println("sub.getStaticValue() = " + sub.getStaticValue());
    }

}

输出

sup.value = 1
sup.staticValue = 10
sup.getValue() = 2
sup.getStaticValue() = 10
sub.value = 2
sub.staticValue = 20
sub.getValue() = 2
sub.getStaticValue() = 20

猜你喜欢

转载自blog.csdn.net/chennai1101/article/details/84287021