Hello frns!!! Here is my problem. I have a very simple superclass with a private int count and public getter and setter for the int.
Now i extend this superclass. My subclass will not inherit the int count, but it will inherit the methods setCount and getCount. So what will happen if in my subclass, i try calling methods setCount and getCount. Answer is, "nothing Exceptional happens".
Here is my SuperClass
And here comes the baby SubClass
My question is, if count is not available with subClass, then what were setCount and getCount methods were setting and getting.
count is not accessible in the subclass, because it is private.
However, the methods getCount and setCountare accessible in the subclass, because they are public. They're also inherited from the superclass.
If you call these methods on an instance of the subclass (and you haven't overridden these methods in the subclass) the code in the superclass is called. The code in the superclass can ofcourse access the variable count that's in the superclass.
When a method is inherited, it does not mean that a copy of the method is automatically made in the subclass - it sounds like you're thinking that inheritance works something like that.
Exactly!!! I thought copy of public methods are made and put into subclasses. But it seems that when i call a certain inherited (non-overridden) method from a subclass, then the method of superclass is called and it operates on the variables of superclass only. I think a major confusion is resolved. Thanks.
But some confusion is still lying. What you are saying means the getCount method of superclass is being called and it gives me the value of int count that lies in superclass. In the getCount method of superclass, i did
And when i call the getCount from subclass, system.out.println on first line tells me, that it has the object of subClass, and the second line prints the value of this.count (so it should be ,count of subclass, which doesnt actually exist) which is actually the value of count in superclass. [ December 04, 2006: Message edited by: Nitin Nigam ]
the basic principle is that we cant access private variable outside the class or scope . there will be no problem in overriding those methods but you cant access the count variable in getCount() as count is declared private.