• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Confused

 
Ranch Hand
Posts: 143
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class B{
protected int x;
B(){ x = 10;}
B(int a){ x = a;}
void m1(){x = 20;}
void m1(int x){this.x = x;}
}
public class A {
int x;
A(){x = 20;}
A(int x){this.x = x;}
void m1(B x){this.x = x.x++;}
public static void main(String arf[]){
A x = new A(20);
B y = new B();
System.out.println(x.x);
x.m1(y);
System.out.println(x.x);
y.m1(30);
System.out.println(y.x);
((A)x).m1(y);
System.out.println(y.x);
}
}
a. 20 10 20 20
b. 20 10 30 31
c. 20 10 20 21
d. 20 20 30 31
e. Compiler error or run time error.
f. None of the above, it will give another output.

Answer is b, pls help to explain the sequence

-Arun
 
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Arun Pai:
pls help to explain the sequence


Note that neither class extends the other, so the methods will be picked up strictly based on reference type:
Let's keep a record of x.x and x.y values after each statement:
>>> x.x = 0, y.x = 0 //class initialization
A x = new A(20);
>>> x.x = 20, y.x = 0
B y = new B();
>>> x.x = 20, y.x = 10
System.out.println(x.x); >>> prints 20
x.m1(y); // m1 in A is invoked because x is instanceof A
>>> x.x = 10, y.x = 11
System.out.println(x.x); >>> prints 10
y.m1(30); // m1 in B is invoked because y is instanceof B
>>> x.x = 10, y.x = 30
System.out.println(y.x); >>> prints 30
((A)x).m1(y); // The casting does nothing. m1 in A is invoked
>>> x.x = 30, y.x = 31
System.out.println(y.x); >>> prints 31
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic