Spaces:
Running
Running
CONSTRUCTOR
Browse files
Week 4: Writing classes/01a Class and object
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
class defines the
|
| 2 |
+
- structure of the object's data content and
|
| 3 |
+
- the operations that can be performed on it
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
use 'class' to model
|
| 7 |
+
- physical things (such as a student, a car, or a holiday share),
|
| 8 |
+
- conceptual things (such as a bank account, a student record, a network connection), and
|
| 9 |
+
- often things that have no real-world equivalent - such as a key-value pair to be used as a parameter
|
| 10 |
+
|
| 11 |
+
1 class
|
| 12 |
+
- create 1/more objects
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
======================================
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
Creating objects from class
|
| 21 |
+
|
| 22 |
+
To construct an object, you call a class's dedicated method, the CONSTRUCTOR.
|
| 23 |
+
The constructor RETURNS a NEW OBJECT (usually with parameters) - or, in fact, a REFERENCE to a new object.
|
| 24 |
+
This reference is usually stored in a variable, through which the entity can later be used/changed and observed.
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
For example, to create a new list object, call the ArrayList class constructor:
|
| 28 |
+
|
| 29 |
+
ArrayList<String> nordics = new ArrayList<>();
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
The name of the constructor method is always the same as the name of the class.
|
| 34 |
+
Thus, for example, the 'name of the constructor method' of the 'ArrayList class' is 'ArrayList', and
|
| 35 |
+
the name of the constructor of the Random class is Random.
|
| 36 |
+
|
| 37 |
+
When creating a new object, the 'operator new' is used, which, as its name implies,
|
| 38 |
+
indicates that the intention is to create a new object from the class.
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
In the example, we have initialized the objects of the classes Random and StringBuilder:
|
| 43 |
+
|
| 44 |
+
import java.util.Random;
|
| 45 |
+
|
| 46 |
+
public class TestClass {
|
| 47 |
+
public static void main(String[] args) {
|
| 48 |
+
|
| 49 |
+
// class1
|
| 50 |
+
// New object from the class random
|
| 51 |
+
Random randomizer = new Random();
|
| 52 |
+
|
| 53 |
+
// class2
|
| 54 |
+
// New object from the class stringbuilder
|
| 55 |
+
StringBuilder address = new StringBuilder("Javaroad 12");
|
| 56 |
+
}
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
|