在派生类中重新定义静态成员。 Java的

时间:2014-12-20 06:36:14

标签: java static static-methods

所以我正在读这本书,作者说“静态成员不参与运行时多态性。你不能覆盖派生类中的静态成员,但你可以重新定义它们。”

这是什么意思?你能举个例子吗?

谢谢。

4 个答案:

答案 0 :(得分:4)

如果在子类中重新定义静态成员(方法或变量),则隐藏超类的定义。

public class Super
{
    public static void methodA()
    {

    }
}

public class Sub extends Super
{
    public static void methodA()
    {

    }
}

这里静态methodA在子类中重新定义,但它不会覆盖超类的methodA

致电Sub.methodA会调用Sub' methodA。如果Sub没有methodA,则调用Sub.methodA会调用Super' methodA

答案 1 :(得分:1)

如果在子类中重新定义静态方法,则其调用方法隐藏。静态方法在编译时而不是运行时解析,你可以根据类来调用它们:比如说:

class A {
    public static void mymthod() {}
}

class B extends A {
    public static void mymthod() {}
}

你打电话给:

A a = new B();
a.mymthod();//resolved at compile time and associated with class A (compiler will warn although as static method doesnt necessarily need an object to call)

答案 2 :(得分:1)

你可以用这个

看看
class A {

    static int x = 1;
    int y = 1;

    int f() {
        return 1;
    }

    static int sf() {
        return 1;
    }
}

class B extends A {

    static int x = 2;
    int y = 2;

    int f() {
        return 2;
    }

    static int sf() {
        return 2;
    }

}

public class Test {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        A b = new B();
        System.out.println("A.x=" + ((A) b).x);
        System.out.println("B.x=" + b.x);
        System.out.println("A.y=" + ((A) b).y);
        System.out.println("B.y=" + b.y);
        System.out.println("A.f() = " + ((A) b).f());
        System.out.println("B.f() = " + b.f());
        System.out.println("A.sf() = " + ((A) b).sf());
        System.out.println("B.sf() = " + b.sf());

    }

}

它pprints:

A.x = 1 B.x = 1 A.y = 1 B.y = 1 A.f()= 2 B.f()= 2 A.sf()= 1 B.sf()= 1

人们会期望B.sf打印为2但不打印。

同样的人会认为B.x和B.y打印为2但也没有,因为字段也不是多态的,只是函数。

我不确定这是否具有很大的实用价值,一定会在完成错误后得知这一点。 这可能会在更糟糕的求职面试中被问到。

答案 3 :(得分:0)

子类中的变量隐藏了超类中具有相同名称的变量。

相关问题