When you codify a class, you can often specify the method's name as is in a methodcall statement. For example, the constructor in Listing 2-35's Employee class specifies the name of Employee's setName() method in method-call statement setName(name);.
However, you cannot always call a method by simply specifying its name. For example, you cannot call a class method from another class in this manner. Also, you cannot call a method that is hidden from you. For example, you cannot call a private method from another class.
The following rules will help you learn how to call methods in different contexts, and even if such calling is possible:
■ Specify the name of a class method as is from anywhere within the same class as the class method. Example: main(new String[o]); // No arguments are passed
■ Specify the name of the class method's class, followed by the member access operator, followed by the name of the class method from outside the class provided that its access control permits this form of access—the method is declared public, for example. Example: Math.sin(Math.toRadians(45));
■ Specify the name of an instance method as is from any instance method, constructor, or instance initializer in the same class as the instance field. Example: processLine(line);
■ Specify an object reference, followed by the member access operator, followed by the name of the instance field from any class method or class initializer within the same class as the instance field, or from outside the class provided that its access control permits this form of access. Example: CheckingAccount ca = new CheckingAccount("John Doe"); ca.printBalance();
Although the latter rule might seem to imply that you can call an instance method from a class context, this is not the case. Instead, you call the method from an object context.
NOTE: Field access and method call rules are combined in statement System.out.println();, where the leftmost member access operator accesses the out class field (of type PrintStream) in the System class, and where the rightmost member access operator calls this field's println() method.
Was this article helpful?