通过java中的静态方法访问私有变量

Cap*_*orn 3 java static-methods private-members

假设我有以下java类:
A类:

public class A { 
    private int x; 

    public A(int x){ 
        this.x = x; 
    } 

    public static void main(String[] args) { 
        A a = new A(1); 
        B b = new B(1,2); 
        System.out.println((A)b.x);
    }
}
Run Code Online (Sandbox Code Playgroud)

B级:

public class B extends A { 
    public int y; 

    public B(int x, int y){ 
        super(x); 
        this.y = y; 
    } 
}
Run Code Online (Sandbox Code Playgroud)

为什么编译器会在此行上标记对x的访问

System.out.println((A)b.x);
Run Code Online (Sandbox Code Playgroud)

作为一个错误,即使我试图从定义它的类访问x?

是因为:
1.使用多态?
2.使用静态方法?
3.使用主要方法?

Kee*_*san 7

你需要让它((A)b).x正确地输入它

注意:您正在尝试键入强制转换属性x以进行键入A.那是错误!