KaiquanMah commited on
Commit
9be3a92
·
verified ·
1 Parent(s): 7f20352

Create 12A Object's inside calls

Browse files
Week 4: Writing classes/12A Object's inside calls ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ The METHODS of an object can also CALL OTHER METHODS of the SAME OBJECT.
3
+ This is important to ensure modularity:
4
+ this way the same code does not need to be written several times inside the same class, but the same methods can be used.
5
+
6
+ A method within the same class is called by its name WITHOUT a PREFIX
7
+ (although you CAN PREFIX the call with the keyword 'this' if you wish, IF it makes the code CLEARER).
8
+
9
+ An example where the constructor of the 'Car' class calls the setting method
10
+ to check if the registration number is in the allowed format
11
+ (the actual check is quite loose in the implementation, though) - this way,
12
+ the check does NOt NEED to be IMPLEMENTed SEPARATELY for the constructor and the setting method:
13
+
14
+ class Car {
15
+ // CLASS ATTRIBUTES
16
+ private String brand;
17
+ private String licensePlate;
18
+
19
+ // CONSTRUCTOR
20
+ public Car(String brand, String licensePlate) {
21
+ this.brand = brand;
22
+ // Also
23
+ // this.setLicensePlate(licensePlate);
24
+ // would be ok
25
+ setLicensePlate(licensePlate);
26
+ }
27
+
28
+ public String getBrand() {
29
+ return brand;
30
+ }
31
+
32
+ public void setBrand(String brand) {
33
+ this.brand = brand;
34
+ }
35
+
36
+ public String getLicensePlate() {
37
+ return licensePlate;
38
+ }
39
+
40
+ public void setLicensePlate(String licensePlate) {
41
+ if (licensePlate.length() >= 3 && licensePlate.contains("-")) {
42
+ this.licensePlate = licensePlate;
43
+ }
44
+ }
45
+ }
46
+
47
+
48
+
49
+ // then save as TestClass.java
50
+ // move 'TestClass' code segment above 'Car' code segment
51
+ Testclass:
52
+ public class TestClass {
53
+ public static void main(String[] args) {
54
+ // this is ok
55
+ Car car = new Car("Lada", "abc-123");
56
+ System.out.println(car.getLicensePlate());
57
+
58
+ // this is NOT 'SET'
59
+ // because it fails the format check
60
+ car.setLicensePlate("x123");
61
+ System.out.println(car.getLicensePlate());
62
+
63
+ // this is NOT CREATED
64
+ // because it fails the format check
65
+ Car car2 = new Car("Mersu", "x-");
66
+ System.out.println(car2.getLicensePlate());
67
+ }
68
+ }
69
+
70
+ Program outputs:
71
+ abc-123
72
+ abc-123
73
+ null
74
+
75
+
76
+
77
+