• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

base casting

 
Shubh Bhat
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why is the answer i=1 and j=2.
I mean j=2 is fine but how can i be equal to 1 it should be 0, I think.
please explain, appreciate it!
class A {
protected int mv;
protected int getMv() {
int mv = 1;
return mv;
}
}
class B extends Class A {
public int mv;
protected int getMv() {
int mv = 2;
return mv;
}
static public void main(String s[]) {
B b = new B();
int i = ((A)b).mv;
int j = ((A)b).getMv();
System.out.println("i="+i+", j="+j);
}
 
Barkat Mardhani
Ranch Hand
Posts: 787
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Subsh:
For me following code printed i = 0 and j = 2. I had to make couple of correction in the code. For next time, it will be easier if you paste your actual code that is printing what you saying it is printing. Even better if you paste your code using code button below. That I do not have to spend time indenting your code
 
Bishal P
Ranch Hand
Posts: 43
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes you are right. The program did print i=0,j=2. Shubh, you should send an email to the person who has written the question to correct his mistake.
 
sun moon
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can pls explain me what is ((A)b) signifies above
 
Valentin Crettaz
Gold Digger
Sheriff
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(A)b casts b (of type B) to type A.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic