File size: 2,158 Bytes
9be3a92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
66
67
68
69
70
71
72
73
74
75
76
77
78

The METHODS of an object can also CALL OTHER METHODS of the SAME OBJECT. 
This is important to ensure modularity: 
this way the same code does not need to be written several times inside the same class, but the same methods can be used.

A method within the same class is called by its name WITHOUT a PREFIX 
(although you CAN PREFIX the call with the keyword 'this' if you wish, IF it makes the code CLEARER).

An example where the constructor of the 'Car' class calls the setting method 
to check if the registration number is in the allowed format 
(the actual check is quite loose in the implementation, though) - this way, 
the check does NOt NEED to be IMPLEMENTed SEPARATELY for the constructor and the setting method:

class Car {
    // CLASS ATTRIBUTES
    private String brand;
    private String licensePlate;

    // CONSTRUCTOR
    public Car(String brand, String licensePlate) {
        this.brand = brand;
        // Also
        // this.setLicensePlate(licensePlate); 
        // would be ok
        setLicensePlate(licensePlate);
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public String getLicensePlate() {
        return licensePlate;
    }

    public void setLicensePlate(String licensePlate) {
        if (licensePlate.length() >= 3 && licensePlate.contains("-")) {
            this.licensePlate = licensePlate;
        } 
    }  
}



// then save as TestClass.java
// move 'TestClass' code segment above 'Car' code segment
Testclass:
public class TestClass {
    public static void main(String[] args) {
        // this is ok
        Car car = new Car("Lada", "abc-123");
        System.out.println(car.getLicensePlate());
        
        // this is NOT 'SET'
        // because it fails the format check
        car.setLicensePlate("x123");
        System.out.println(car.getLicensePlate());
        
        // this is NOT CREATED
        // because it fails the format check
        Car car2 = new Car("Mersu", "x-");
        System.out.println(car2.getLicensePlate());    
    }
}

Program outputs:
abc-123
abc-123
null