Spaces:
Running
Running
| class defines the | |
| - structure of the object's data content and | |
| - the operations that can be performed on it | |
| use 'class' to model | |
| - physical things (such as a student, a car, or a holiday share), | |
| - conceptual things (such as a bank account, a student record, a network connection), and | |
| - often things that have no real-world equivalent - such as a key-value pair to be used as a parameter | |
| 1 class | |
| - create 1/more objects | |
| ====================================== | |
| Creating objects from class | |
| To construct an object, you call a class's dedicated method, the CONSTRUCTOR. | |
| The constructor RETURNS a NEW OBJECT (usually with parameters) - or, in fact, a REFERENCE to a new object. | |
| This reference is usually stored in a variable, through which the entity can later be used/changed and observed. | |
| For example, to create a new list object, call the ArrayList class constructor: | |
| ArrayList<String> nordics = new ArrayList<>(); | |
| The name of the constructor method is always the same as the name of the class. | |
| Thus, for example, the 'name of the constructor method' of the 'ArrayList class' is 'ArrayList', and | |
| the name of the constructor of the Random class is Random. | |
| When creating a new object, the 'operator new' is used, which, as its name implies, | |
| indicates that the intention is to create a new object from the class. | |
| In the example, we have initialized the objects of the classes Random and StringBuilder: | |
| import java.util.Random; | |
| public class TestClass { | |
| public static void main(String[] args) { | |
| // class1 | |
| // New object from the class random | |
| Random randomizer = new Random(); | |
| // class2 | |
| // New object from the class stringbuilder | |
| StringBuilder address = new StringBuilder("Javaroad 12"); | |
| } | |
| } | |