To read a variable using a object... where there is only two class. There are four way of creating a object. Here they are. 1. This is the simplest way. 2. parent reference ,child object. you can access parent class ivar 3. This again simple. But cannot access Parent ivar 4. Compiles but does not run,because the compiler checks only one thing that is if they both are of the same inheritance tree.
Parent p= new Parent(); // one System.out.println(p.ivar); */
Parent p= new child(); // two System.out.println(p.ivar);
child c= new child(); // three System.out.println(c.ivar);
child c= new Parent(); // Four , compiles but does not run. System.out.println(c.ivar);
Joined: Sep 08, 2008
Here we not assign parent class reference to child class. It will not compile.
i am afraid how come the fourth one in the previous post getting compiled also.it is a compilation error..See here child is extending parent that means child is a parent not vice versa . So according to me 4 th should give the compilation error(Cannot convert from Parent to chld).
And, ramkumar chennai, pleas use the code button; you can see how much easier your code will be to read.
Joined: Oct 13, 2005
You are incorrect calling the first ivar "parent class variable."
"Parent" is not the approved Java term; you ought to say superclass.
It is not a "class" variable; it belongs to the instance (object). If you are writing object-oriented programming you ought to try to gain access from an object, not from the main method which isn't part of an object.
So it ought to read something like "superclass instance field." When you read it like that, I hope you will take a hint as to how you can gain access to a "superclass instance field" from a "subclass instance method."