Java Reference
In-Depth Information
14. public String getName() {
15. return name;
16. }
17.
18. public int getId() {
19. return id;
20. }
21.
22. private void setId(int id) {
23. if(id > 0) {
24. this.id = id;
25. }
26. }
27.
28. public void processOrder(String itemName) {
29. System.out.println(this.getName() + “ is ordering a “
30. + itemName);
31. }
32.}
Invoking an Instance Method Requires a Reference
Notice that every instance method call in Java requires a reference. Even within a class
we have to use the this reference to invoke another method in the same class, although
the this reference is not required because the compiler adds it implicitly when you leave
it off. For example, in the Customer class the this reference is explicitly denoted on lines
7 and 29, while on line 6 the this reference is implied and the compiler adds it behind the
scenes, resulting in this.setId(id) .
Examine the following statements. Do they compile and, if yes, what is the result?
41. Customer c = null;
42. c.setName(“Sherlock Holmes”);
43. System.out.println(c.getName());
You might be surprised to fi nd out that this code compiles fi ne, even though it does
not make sense to invoke setName and getName because no Customer objects have been
instantiated yet. Without any Customer objects in memory, there are no setName and
getName methods to invoke. Because c is null and does not point to an actual Customer
object, the statement on line 42 generates a NullPointerException .
Search WWH ::




Custom Search