java 代码编译继承扩展

java code compilation heritage extends

此代码存在编译问题。我如何获得 a.f()

class A {
    int i = 1;

    int f() {
        return i;
    }

    static char g() {
        return 'A';
    }
}

class B extends A {
    int i = 2;

    int f() {
        return -i;
    }

    static char g() {
        return 'B';
    }
}

class Test {
    public static void main(String args[]) {
        B b = new B();
        System.out.println(b.i);
        System.out.println(b.f());
        System.out.println(b.g());
        System.out.println(B.g());
        A a = b;
        System.out.println(a.i);
        System.out.println(a.f());
        System.out.println(a.g());
        System.out.println(A.g());
    }
}

这是结果

2
-2
B
B
1
-2
A
A

您没有为您的 class 成员指定任何访问修饰符,因此它只有默认或包级别的访问权限,子 classes

不可用
Modifier    Class Package Subclass World
public      Y     Y       Y        Y 
protected   Y     Y       Y        N 
no modifier Y     Y       N        N 
private     Y     N       N        N 

有关详细信息,请参阅 here

如果您将 f() 的签名更改为 protected int f() 那么它应该可以工作

当然你和 class 的其他成员也有同样的问题所以这取决于你如何控制这个

覆盖仅适用于实例方法,不适用于变量。因此,当您从 class A 的实例中获取变量 i 时,您会从这个 Class 中获取值。 class B.

的实例也是如此

但是你可以在构造函数中重新初始化i的值,例如:

class B extends A {

public B() {
    i=2;
}

int f() {
    return -i;
}

static char g() {
    return 'B';
}