• Post Reply Bookmark Topic Watch Topic
  • New Topic

how can 300 be the answer  RSS feed

 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Here is this code that I can't arrive to the answer of 300. The explanation states that the second call to the addMe() is the same as the first! But, I see it as calling the myChi.addMe() that takes a myChi type?

class MyParent {
int x,y;
MyParent(int x, int y) {
this.x = x;
this.y = y;
}
public int addMe(int x, int y) {
return this.x + x, y + this.y;
}
public int addMe(MyParent myPar) {
return addMe(myPar.x , myPar.y);
}
}

class MyChild extends MyParent {
int z;
MyChild (int x, int y, int z) {
super(x,y);
this.z = z;
}
public int addMe( int x, int y, int z){
return this.x + x + this.y + y + this.z + z ;
}
public int addMe(MyChild myChi) {
return addMe(MyChi.x + MyChi.y + MyChi.z);
}
public int addMe(int x, inty) {
return this.x + x + this.y + y;
}
}

public class MySomeOne {
public static void main(String [] args) {
MyChild myChi = new MyChild(10,20,30);
MyParent myPar = new MyParent(10,20);

int x = myChi.addMe(10,20,30);
int y = myChi.addMe(myChi);
int z = myPar.addMe(myPar);
System.out.println(x + y + z);
}
}

Whew, that is the bear that has got me stumped. I'm thinking that second call is a call to the addMe(MyChild myChi) constructor because it takes the object of a MyChild type?
 
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use code tags. You can add them to the above post by using the edit button at the top right. Thanks!
 
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code you've posted wouldn't even compile; the method addMe() in MyParent uses an invalid comma operator:



Secondly, none of the methods named "addMe" are constructors, so I'm not sure I'm following your discussion. A constructor always has the same name as the class in which it appears, and has no return type.

Finally, the two overloaded addMe() methods in MyChild both return the sum of the x, y, and z members along with either the three int arguments, or the x, y, and z members of the single MyChild argument. Since the members of the "myChi" object have the same values as the three ints that are passed to the previous call (10, 20, 30) I agree that those two calls should return the same value.
 
Ranch Hand
Posts: 502
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does your code even compile?
Please fix compilation errors and post again
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!