Monday 13 June 2016

Objects in Java: Accessing Fields and Methods

Inside a class, we can access variables and call methods of the class directly by name. Here’s an example that expands on our Pendulum:
 class Pendulum {  
 ...  
 void resetEverything() {mass = 1.0;  
 length = 1.0;  
 cycles = 0;  
 ...  
 float startingPosition = getPosition( 0.0 );  
 }  
 ...  
 }  
Other classes access members of an object through a reference, using the dot selector notation that we discussed in the last chapter:
 class TextBook {  
 ...  
 void showPendulum() {  
 Pendulum bob = new Pendulum();  
 ...  
 int i = bob.cycles;  
 bob.resetEverything();  
 bob.mass = 1.01;  
 ...  
 }  
 ...  
 }  
Here we have created a second class, TextBook, that uses a Pendulum object. It creates an instance in showPendulum() and then invokes methods and accesses variables of the object through the reference bob. Several factors affect whether class members can be accessed from another class. You can use the visibility modifiers public, private, and protected to control access; classes can also be placed into a package, which affects their scope. The private modifier, for example, designates a variable or method for use only by other members of the class itself. In the previous example, we could change the declaration of our variable cy cles to private:
 class Pendulum {  
 ...  
 private int cycles;  
 ...  
Now we can’t access cycles from TextBook:
 class TextBook {  
 ...  
 void showPendulum() {  
 ...  
 int i = bob.cycles; // Compile-time error  
If we still need to access cycles in some capacity, we might add a public getCycles() method to the Pendulum class. (Creating accessor methods like this is a good design rule because it allows future flexibility in changing the type or behavior of the value.) We’ll take a detailed look at packages, access modifiers, and how they affect the visibility of variables and methods.

0 comments:

Post a Comment