Salve, ho recuperato questo codice che fa parte di un esame di certificazione.
codice:
class Vehicle {
String type = "4W";
int maxSpeed = 100;
Vehicle(String type, int maxSpeed) {
this.type = type;
this.maxSpeed = maxSpeed;
}
}
class Car extends Vehicle {
String trans;
Car(String trans) {
this.trans = trans; // line 1
}
Car(String type, int maxSpeed, String trans) {
super(type, maxSpeed);
this(trans); // line 2
}
}
public class Test {
public static void main(String args[]) {
Car c1 = new Car("Auto");
Car c2 = new Car("4W", 150, "Manual");
System.out.println(c1.type + " " + c1.maxSpeed + " " + c1.trans);
System.out.println(c2.type + " " + c2.maxSpeed + " " + c2.trans);
}
}
Risultano esserci due errori. Quello su line 2 è chiaro (super() e this() richiedono entrambi di essere la prima istruzione di un costruttore...), mentre non mi è chiaro perché il compilatore lamenti, a proposito di line 1:
Test.java:14: error: constructor Vehicle in class Vehicle cannot be applied to given types; Car(String trans) {
^
required: String,int
found: no arguments
reason: actual and formal argument lists differ in length
L'istanza c1 è di tipo Car, e Car ha il proprio costruttore a un parametro String, perché Java chiama in causa il costruttore della superclasse?