Reputation: 1873
public class Shape{
public int xPos = 10;
public int yPos = 20;
Shape(){
}
public int getXpos(){
return xPos;
}
public void setXpos(int x){
this.xPos = x;
}
public int getYpos(){
return yPos;
}
public void setYpos(int y){
this.yPos = y;
}
}
public class Shape1 extends Shape{
Shape1(){
xPos = 100;
yPos = 200;
}
}
public class Test{
public static void main(String[] args) {
Shape1 shape1 = new Shape1();
System.out.println(shape1.getXpos());
}
}
Why am I getting 10 as a result instead 100?
Upvotes: 1
Views: 132
Reputation: 500773
Now my question is: Why am I getting 10 as a result instead 100?
The code as presented prints out 100. The most likely explanation is that you're not running the code that you say you're running. This could happen due to copy-and-paste errors, deployment problems etc.
One little-known but nasty way in which your code could be subtly modified to print 10
is by adding void
in front of the Shape1
's constructor:
void Shape1() {
xPos = 100;
yPos = 200;
}
This transforms Shape1()
from a constructor into a normal method (which doesn't automatically get called during object construction).
My compiler accepts this modification, and the code prints out 10
when I run it.
I actually once had to deal with a real bug caused by this. Took a little while to spot, I can tell you.
Upvotes: 4