Search code examples
javastatic-methodsprivate-members

Accessing a private variable through static method in java


Let say I have the following java classes:
Class 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);
    }
}

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 marks the access to x on this line

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

as an error, even though I'm trying to access x from the class in which it is defined?

Is it because of:
1. the use of polymorphism?
2. the use of a static method?
3. the use of the main method?


Solution

  • You need to make it ((A)b).x to properly type cast it

    Note : You are trying to type cast the property x to type A. That's the error!