如何覆盖变量

kri*_*hna 1 java variables static overriding

package com.mycompany.myproject.mypkg;

interface MyInterface {
    public static final int k = 9;
}

class MyClass implements MyInterface {
    // int k = 89;
}

public class SampleThree extends MyClass {
    static int k = 90;

    public static void main(String args[]) {
        MyClass object = new SampleThree();
        System.out.println(object.k);
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么上面的程序打印'9'而不是'90'?

如何在Java中覆盖静态和成员变量?

Boz*_*zho 5

因为字段不支持多态.MyClass.k9(并且object被引用MyClass).SampleThree.k会给你的90.每个类都有自己的一组变量.

(顺便说一句,IDE会在这里给你一个警告,你要通过一个实例而不是它的类访问一个静态变量.)