Question

I'm trying to extend my Vehicle class to a HumanPowered class -- Has a field for calories per hour. This is my first time trying to extend a class so I'm a bit confused here.

class Vehicle
{
String description;
String idNumber;
int numWheels;

public Vehicle(String aDescription, String aIdNumber, int aNumWheels)
{
    description = aDescription;
    idNumber = aIdNumber;
    numWheels = aNumWheels;
}
void setDescription (String aDescription)
{
    description = aDescription;
}
void setIdNumber (String aIdNumber)
{
    idNumber = aIdNumber;
}
void setNumWheels (int aNumWheels)
{
    numWheels = aNumWheels;
}
public String getDescription()
{
    return description;
}
public String getIdNumber()
{
    return idNumber;
}
public int getNumWheels()
{
    return numWheels;
}
public String toString()
{
    String result= String.format("ID: %s Description: %s Wheels: %d",idNumber,description,numWheels);
    return result;
}

}
class humanPowered extends Vehicle
{
int calories;
public humanPowered(String aDescription, String aIdNumber, int aNumWheels, int aCalories) //Error here
{
    description = aDescription;
    idNumber = aIdNumber;
    numWheels = aNumWheels;
    calories = aCalories;   
}
void setCalories (int aCalories)
{
    calories = aCalories;
}
public int getCalories()
{
    return calories;
}
public String toString()
{
    String result= String.format("ID: %s Description: %s Wheels: %d Calories per Hour: %d",idNumber,description,numWheels, calories);
    return result;
}
}

I'm getting an error marked above on my constructor for my humanPowered class saying "Implicit super constructor Vehicle() is undefined. Must explicitly invoke another constructor." I can't figure out where I'm going wrong here. Thanks for any and all help!

Was it helpful?

Solution

Vehicle don't have default constructor hence you have to call its constructor form humanPowered class passing required arguments at the first line of its constructor.

public humanPowered(String aDescription, String aIdNumber, int aNumWheels, int aCalories)    
{
   super(aDescription,aIdNumber,aNumWheels);
   ...//other code
}

Points to remember:

  • Every class have default constructor that is no-argument constructor
  • If class creates a constructor passing arguments then by default constructor is not created
  • Each constructor by default calls default constructor of its super-class
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top