Spaces:
Running
Running
| 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 | |