Identifying invalid calls
Hey guys, quick question here - I'm supposed to identify which calls to the constructor are invalid - here's the code. Note this is not compilable, it's just the example that the book gives.
My first thoughts was down in the main method where it's declaring myCar1 = new Car();, etc. Though I'm not 100% sure.
Code :
class Car {
public String make;
protected int weight;
private String color;
private Car (String make, int weight, String color) {
this.make = make;
this.weight = weight;
this.color = color;
}
public Car () {
this ("unknown", -1, "white");
}
class ElectricCar extends Car {
private int rechargeHour;
public ElectricCar() {
this(10);
}
private ElectricCar(int charge) {
super();
rechargeHour = charge;
}
}
class TestMain {
public static void main (String[] args) {
Car myCar1, myCar2;
ElectricCar myElec1, myElec2;
myCar1 = new Car();
myCar2 = new Car("Ford", 1200, "Green");
myElec1 = new ElectricCar();
myElec2 = new ElectricCar(15);
}
}
Thanks
Re: Identifying invalid calls
Did they indeed put the ElectricCar class inside of the Car class? If that's the case, that's probably the problem. Normally when you extend a class you don't place the extending class inside the original class (actually, it's not often that a class gets placed inside another class). If it's suppose to be placed inside, then the two calls to the ElectricCar constructors are incorrect. They must be referenced from an existing instance of the Car class. For example:
Code Java:
myElec1 = myCar1.new ElectricCar();
As for the Car constructors, look at the ones declared inside the Car class and the ones invoked. do the signatures match up?
Ex., these would match up:
Code Java:
public SomeClass(String a)
{
}
public SomeClass()
{
}
// to call 1st constructor
SomeClass c = new SomeClass("hello");