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;
}
}
setName()looks a little problematic.Peta superclass ofMammalfor instance, you are saying that a mammal is a pet. There are tons of mammals that can't be domesticated. Also, someFishcan be pets. Therefore, it is probably best to makePetan interface instead of a class. Remember, the scope narrows when you get down the inheritance tree. That means that a subclass is a more specific type than its superclass. This rule is not observed in your example. I know it has nothing to do with your problem, but a needed observation.