【问题标题】:java code compilation heritage extendsjava代码编译遗产扩展
【发布时间】:2015-11-11 07:27:24
【问题描述】:

此代码存在编译问题。如何获得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

【问题讨论】:

    标签: java access-modifiers


    【解决方案1】:

    覆盖只是用于实例方法,而不是用于变量。因此,当您从类 A 的实例中获取变量 i 时,您会从该类中获取值。与 B 类的实例相同。

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

    class B extends A {
    
    public B() {
        i=2;
    }
    
    int f() {
        return -i;
    }
    
    static char g() {
        return 'B';
    }
    

    【讨论】:

      【解决方案2】:

      你没有为你的类成员指定任何访问修饰符,所以它只有默认或包级别的访问权限,对子类不可用

      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(),那么它应该可以工作

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多