Thread: Java Help
View Single Post
Old 04-19-07, 11:15 PM   #5
rhink
Registered User
 
Join Date: Jul 2005
Posts: 434
Default Re: Java Help

heh that sucks, arrays are the easy stuff.

I don't think you're quite understanding inheritance. In your example "a" is its own unique variable or object. It points to a different spot in memory than "b". There's no way for "b" to know what's going on in "a".

Inheritance means that your class "B" 'inherits' all methods and attributes of class "A". So when you do a "new B()", you create a new object that contains all of the variables and methods in class "A", plus whatever else you've defined.

I'll go through your example step by step to show you what I mean...
Code:
A a = new A();
"a" now contains variable ivar, initialized to 0.

Code:
B b = new B();
"b" now has its own copy of ivar, and ivar2, both initialized to 0

Code:
a.setIvar(25);
Now "a.ivar" is 25, "b.ivar" is 0, "b.ivar2" is 0.

Code:
b.setIvar2(35);
Now "a.ivar" is 25, "b.ivar" is 0, "b.ivar2" is 35.

Code:
b.d1();
You print out b's copy of ivar and ivar2- so you print "0, 35".

Now do you see why that doesn't work?
rhink is offline   Reply With Quote