Accessing private variables through static methods in Java

Suppose I have the following Java classes:

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);
    }
}

Class B:

public class B extends A { 
    public int y; 

    public B(int x,int y){ 
        super(x); 
        this.y = y; 
    } 
}

Why does the compiler mark access to X on this line

System.out.println((A)b.x);

As an error, even if I try to access x from the class that defines it?

Because: 1 Use polymorphism? 2. Using static methods? 3. Main methods used?

Solution

You need to do (a) b) X to enter it correctly

Note: you are trying to convert property X type to type A. This is an error!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>