aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes what is wrong ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "what is wrong ?" Watch "what is wrong ?" New topic
Author

what is wrong ?

chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
Hi,
In the following code, I intend to modify the i in class A to 50.
When the program runs, to my surprise, the i in class A stay 5, but the i in class B becomes 50. ie the output is
5
50
Could someone tell me what is the problem with my code ?
thanks

class A{
protected int i = 5;
public int getI() { return i; }
}
public class B extends A{
public void process(){super.i = (super.i)*10;}
public static void main(String[] args){
A a = new A();
B b = new B();
b.process();
System.out.println(a.getI());
System.out.println(b.getI());
}
}


not so smart guy still curious to learn new stuff every now and then
Sean Casey
Ranch Hand

Joined: Dec 16, 2000
Posts: 625
to get the output you're looking for you would need to alter the process method as so:
public void process(){i *= 50;}
This way you're altering the value of i and then storing it with the reference i.
chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
Sean,
I tried your suggestion, the output still the same :
5
50
which means the i in instance a is 5 when I intent to chage it to 50, the i in instance b is 50 when I intent to keep it 5.
chi-chih
Originally posted by Sean Casey:
to get the output you're looking for you would need to alter the process method as so:
public void process(){i *= 50;}
This way you're altering the value of i and then storing it with the reference i.

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
chichih,
Do take a look at this code.



Shyam
[This message has been edited by Shyamsundar Gururaj (edited September 12, 2001).]
chi Lin
Ranch Hand

Joined: Aug 24, 2001
Posts: 348
Shyam,
Compare and play with these two set of codes, I start to get some more sense about this issue even not 100% clear at this moment.
thanks for the help.
chi-chih

Originally posted by Shyamsundar Gururaj:
[B]chichih,
Do take a look at this code.



Shyam
[This message has been edited by Shyamsundar Gururaj (edited September 12, 2001).][/B]

Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
ChiChih,
Oops I am sorry! I did not read your initial post too well. I thought that you wanted to change both the "i"s to 50.
Will work on it.
Shyam
[This message has been edited by Shyamsundar Gururaj (edited September 12, 2001).]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: what is wrong ?