This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The problem is that you are accessing the instance variable from the main method, which is a static method. Read the error message again : non-static variable x cannot be referenced from a static context. I don't know if you have already studies what static variables and static methods are. Try to make a public non static method in Child, and try System.out.println("x is " + x); again.
Hello sandra Bachan , this is the most frequent mistake encountered by JAVA learners.
Just to follow one rule :
Non-Static members cannot be accessed from Static context ie Static methods directly without referring to any object.
Reasoning :- Static members could exist before object creation.
So when you are trying to access variable x which is inherited from the parent class, it is still non- static. You try to access a non-static variable from the static main method and hence the error. Because at that time if suppose,say, 100 objects of the child class already exists on the heap, then compiler complains because it does not resolve that whose x are you trying to refer .
But But But if you say i am referring to object number ,say 75, then you would say ob75.x , now compiler knows that you are referring to x which exists inside object75, and hence it is allowed.