All methods will have an associated access that defines how and if the method can be called outside of the class in which it is defined. You can either specify the access explicitly with an access modifier or the method will be given default access if no access is specified. The four types of access a method can have are public , protected , private , and default.
The method access types and what they mean are summarized in Table 9.1. All methods are freely accessible inside the class in which they are defined. It is only outside of their class that access modifiers come into play. Table 9.1. Method Accessibility
Example: Method AccessThe AccessDemo class defines two methods. The getTotalCost() method is meant to be accessed outside of the AccessDemo class and therefore is given public access. The secretMethod() method is intended for internal use only. To prevent outside access of this method, it is given private access. public class AccessDemo { private double totalCost, fixedCost; public AccessDemo(double fixed) { fixedCost = fixed; } // The getTotalCost() method is given public access. // The secretMethod() method is given private access. public double getTotalCost() { totalCost = fixedCost + secretMethod(); return totalCost; } private double secretMethod() { return 1.4*fixedCost; } } We next write a driver program for the AccessDemo class. The AccessDriver class creates an AccessDemo object. You can't call the secretMethod() method outside of the AccessDemo class. Any attempt to do so will result in a compiler error. The getTotalCost() method is public and can be called outside of the AccessDemo class. public class AccessDriver { public static void main(String args[]) { AccessDemo demo = new AccessDemo(1234.56); // Can't access the private method // demo.secretMethod(); // Can access the public method System.out.println("cost is " + demo.getTotalCost()); } } Output ” cost is 2962.944 |