Monday, August 20, 2007

about private and public variable?

Java uses three explicit keywords and one implied keyword to set the boundaries in a class: public, private, and protected. The default access specifier for the names of variables and methods is “package visibility” or “friendly,” which means that all the other classes in the current package have access to them. (Packages are Java's way of grouping classes to make libraries and will be discussed later.) The access specifier public means that the variables and methods are available from any package; private implies that the variables and methods can only be accessed inside methods of the same class. The keyword protected indicates additional access to variables and methods that are available to subclasses. We will clarify its meaning when we discuss inheritance.
One reason to make a variable private is to restrict access to it. Access becomes an issue for threading which refers to the sequence of execution of program code. For example, we would want to avoid changing the value of a variable while another portion of the code is trying to read it. Make x private and see what happens when you run MyApplication.
If we declare x, y, and mass as private variables, we have to include explicit methods in Particle to allow another class to access the variable information in Particle. For simplicity, we will consider only the variables x and mass. Our Particle class becomes: public class Particle
{
private double x;
private double mass;
public Particle(double x)
{
this(x, 1.0);
}
public Particle(double x, double mass)
{
this.x = x;
this.mass = mass;
}
public double getX()
{
return x;
}
public void setX(double newX)
{
x = newX;
}
public double getWeight()
{
return 9.8*mass;
}
public double distanceFromOrigin()
{
return Math.abs(x);
}
}
Note the new methods getX and setX. They are used in the following. public class MyApplication
{
public static void main(String[] args)
{
Particle p = new Particle(10.0, 2.0);
System.out.println("Distance of particle from origin = " + p.distanceFromOrigin());
System.out.println("x-coordinate = " + p.getX()); // would have written p.x if x were public
System.out.println(weight = " + p.getWeight());
p.setX(3.0); // change value of x
System.out.println("new x-coordinate = " + p.getX());
System.out.println("new distance from origin = " + p.distanceFromOrigin());
}
}
In the following, we will not make variables such as x and y private, because they will be used in so many classes.

No comments: