The following code yields a stack overflow error, can someone tell me why?
(I know how to fix the error, if I reference 'super' instead of 'this' in the add
method, but I am not sure why that works.)
package subclassingVector;
import java.util.Vector;
public class MyVectorSubclass extends Vector<MyModelClass> {
public MyVectorSubclass(){
MyModelClass m = new MyModelClass();
m.setId(2);
this.add(m);
if(this.contains(m)){
System.out.println("contains is true");
}
}
public boolean add(MyModelClass o){
this.add(o);
return true;
}
public boolean contains(Object o){
for(subclassingVector.MyModelClass mmc: this){
if(mmc.equals((MyModelClass) o)){
return true;
}
}
return false;
}
public static void main(String[] args) {
String s = new String("SSEE");
MyVectorSubclass m = new MyVectorSubclass();
}
public class MyModelClass {
private Integer id = null;
public MyModelClass() {
// TODO Auto-generated constructor stub
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}
}
This code calls itself, forever, hence the StackOverflowError:
public boolean add(MyModelClass o){
this.add(o);
return true;
}
The this
represents the instance of the object that the current method is being called on. In fact, the above code, in this context, is precisely the same as:
public boolean add(MyModelClass o){
add(o);
return true;
}
This code does something entirely different:
public boolean add(MyModelClass o){
super.add(o);
return true;
}
That doesn't make a recursive call. That simply calls the implementation of add()
in the base class.
Cory Kendall's comment on the question is very valuable:
If you get a
StackOverflowError
, looking at the stack trace of the Error should be informative; walk through the logic using the given line numbers.
The stack traces of an exception can give you a lot of useful information about the origin of the problem. In this case, the stack trace would clearly show that MyVectorSubClass.add()
is repeatedly calling itself in the case of this.add(o)
.
I suggest taking a look at: