'Stack overflow error in java concerning inheritance
I am working on a project for my intro to java class and am working on inheritance. The problem is with the classes Mammal
and Pet
. When I run the driver class I get a stack overflow error on line 12 where it calls setName(inName)
of Mammal
. Can someone point me in the right direction?
package inlab9;
/**
* Driver for Inlab9.
*
* @author yaw
* @version 14 Nov 2014
*/
public class Driver
{
public static void main(String[] args)
{
Pet p = new Pet("Terrance");
p.printInfo();
System.out.println();
Mammal m = new Mammal();
m.printInfo();
m.setName("Roxie");
m.printInfo();
System.out.println();
Fish f = new Fish("red");
f.printInfo();
f.setName("Shark");
f.printInfo();
System.out.println();
Dog d = new Dog("Watson", "Basset");
d.printInfo();
}
}
package inlab9;
public class Mammal extends Pet {
protected static String name = "Fluffy";
public Mammal(){
super(name);
}
public void setName(String inName){
setName(inName);
}
public void printInfo(){
System.out.println("The pet's name is " +name);
}
}
package inlab9;
public class Pet {
protected String name;
public Pet(String name){
this.name = name;
}
public void printInfo(){
System.out.println("The pets name is " + name);
}
public void setName(String name){
this.name = name;
}
}
Solution 1:[1]
To call the super class method, you should write:
public void setName(String inName){
super.setName(inName);
}
That said, you don't really need to implement setName
in the sub-class if it only calls the super class implementation.
Solution 2:[2]
Your problem is here,in class Mammal
public void setName(String inName){
setName(inName);//<-- recursive class
}
Try instead, if you really want to override it, else don't do it
@Override
public void setName(String inName){
super.setName(inName);
}
Solution 3:[3]
When you call
public void setName(String inName){
setName(inName);
}
you are recursively calling the method and there is no break to stop it, so the stack keeps incrementing until it overflows. You might want to try using the keyword super
before to call the parent class' method:
super.setName(inName);
But since this is a child of a parent with this predefined method, you really don't even need this unless you want this method to do something different. That is the point of inheritance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Eran |
Solution 2 | |
Solution 3 | Luminusss |