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