Spaces:
Running
Running
File size: 1,431 Bytes
02c40fa |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
In the attached program, the class 'Car' is defined.
However, the class lacks a 'constructor'.
Complete the class by writing a constructor to the class, which takes as parameters the
values of the attributes in the order in which they are defined in the class.
import java.util.Random;
public class Test{
public static void main(String[] args){
final Random r = new Random();
System.out.println("Testing to create an object...");
Car c1 = new Car("Datsun", "100A", 1976, 0.8);
Car c2 = new Car("Nissan", "Skyline R34 GT-R", 1995, 2.5);
System.out.println(c1);
System.out.println(c2);
}
}
class Car {
String brand;
String model;
int yearmodel;
double engineCapacity;
//ADD CONSTRUCTOR
public Car(String brand, String model, int yearmodel, double engineCapacity) {
this.brand = brand;
this.model = model;
this.yearmodel = yearmodel;
this.engineCapacity = engineCapacity;
}
@Override
public String toString() {
return "Car [brand=" + brand + ", model=" + model + ", yearmodel=" + yearmodel + ", engineCapacity="
+ engineCapacity + "]";
}
}
Testing to create an object...
Car [brand=Datsun, model=100A, yearmodel=1976, engineCapacity=0.8]
Car [brand=Nissan, model=Skyline R34 GT-R, yearmodel=1995, engineCapacity=2.5]
|