aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confused Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Confused" Watch "Confused" New topic
Author

Confused

Arun Pai
Ranch Hand

Joined: Mar 11, 2002
Posts: 143
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
Doanh Nguyen
Ranch Hand

Joined: Dec 02, 2000
Posts: 45
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confused
 
Similar Threads
pls clarify
Dynamic Binding
explain
general
please help