This is Error is caused by the constructor of your subclass implicitly calling on the default constructor of your base class
Your code is actually doing this:
public class Cat{
public Cat(String name){
super();
setName(name);
}
//other code in the class
}
Because you have defined a constructor in your base class, Animal
, the default constructor no longer existences. So you need can do one of two things:
Add a default constructor that does nothing (or does helps you build your object without the need of passing in any arguments
public class Animal {
String name;
public Animal(){
}
public Animal(String string) {
}
/// other code
}
Or call the base class constructor you did create and modify your subclass constructor to do whatever extra is needed for that subclass.
public class Animal {
private String name;
public Animal(String name){
this.name = name;
}
///other code
}
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
/// other code
}
Something you should think about, when creating subclasses, is the usefulness of inheritance. Having a base class that can do general actions and setup makes it so that subclasses should only do what's unique to them.
If a base class is being used as a label instead of a shared functionality, then it might be best to make the base class an interface. When it comes to constructors you should have any general setup be done in the base class constructor and then set fields that are unique to the subclass in the subclass constructor.
public class Animal {
private String name;
private int legs;
public Animal(String name, int num_of_legs){
this.name = name;
this.legs = num_of_legs;
}
protected int getAnimalLegs(){
return this.legs;
}
/// other code, getters, setters, etc.
}
public class Cat extends Animal {
private int cuteness;
public Cat(String name, int num_of_legs, int level_of_cuteness) {
super(name, num_of_legs);
this.cuteness = level_of_cuteness;
}
/// other code
}
This would set the private variables name and legs on a super class of Cat and make the constructor for Cat only perform actions that relate it's fields i.e. setting the level of cuteness for the Cat object. Also note that you can't call code before you call the super constructor in your subclass constructor. If you do, you will end up with another error.