Spaces:
Running
Running
ClassName variableName = new ClassName("str1", "str2", int3);
Browse files
Week 4: Writing classes/01b. Three objects [FROM CLASS CREATE OBJECTS]
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
A category called Nephew is defined in the programme.
|
| 2 |
+
The class has a constructor which receives the following parameters in order:
|
| 3 |
+
name (string)
|
| 4 |
+
hat colour (string)
|
| 5 |
+
height (integer)
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
Create three objects from the class with the following information:
|
| 9 |
+
name: Dewey, hat color: blue
|
| 10 |
+
name: Huey, hat colour: green
|
| 11 |
+
name: Louie, hat colour: red
|
| 12 |
+
|
| 13 |
+
All objects have a length of 95.
|
| 14 |
+
Save the references of the objects to the variables dewey, huey and louie.
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
import java.util.Random;
|
| 22 |
+
|
| 23 |
+
public class Test {
|
| 24 |
+
public static void main(String[] args) {
|
| 25 |
+
System.out.println("Testing object creation...");
|
| 26 |
+
|
| 27 |
+
//ADD
|
| 28 |
+
Nephew dewey = new Nephew("Dewey", "blue", 95);
|
| 29 |
+
Nephew huey = new Nephew("Huey", "green", 95);
|
| 30 |
+
Nephew louie = new Nephew("Louie", "red", 95);
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
System.out.println("Dewey: " + dewey);
|
| 36 |
+
System.out.println("Huey: " + huey);
|
| 37 |
+
System.out.println("Louie: " + louie);
|
| 38 |
+
}
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
class Nephew {
|
| 42 |
+
private String name;
|
| 43 |
+
private String hatColor;
|
| 44 |
+
private int height;
|
| 45 |
+
|
| 46 |
+
public Nephew(String name, String hatColor, int height) {
|
| 47 |
+
this.name = name;
|
| 48 |
+
this.hatColor = hatColor;
|
| 49 |
+
this.height = height;
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
@Override
|
| 54 |
+
public String toString() {
|
| 55 |
+
return "Nephew [name=" + name + ", hat color=" + hatColor + ", height=" + height + "]";
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
Testing object creation...
|
| 64 |
+
Dewey: Nephew [name=Dewey, hat color=blue, height=95]
|
| 65 |
+
Huey: Nephew [name=Huey, hat color=green, height=95]
|
| 66 |
+
Louie: Nephew [name=Louie, hat color=red, height=95]
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
|