Consider the UML diagram
(from the Enterprise Architect project
file quadcopter.eap)
The corresponding class:
public class Quadcopter
{
private double xLocation, yLocation, xDestination, yDestination;
private double maxSpeed;
public void setLocation(double x, double y)
{
xLocation = x;
yLocation = y;
}
public void setDestination(double x, double y)
{
xDestination = x;
yDestination = y;
}
public double getXDestination()
{
return xDestination;
}
public double getYDestination()
{
return yDestination;
}
public void setMaxSpeed(double maxSpeed)
{
this.maxSpeed = maxSpeed;
}
public void getMaxSpeed()
{
return maxSpeed;
}
public double distanceToDestination()
{
double dx = xLocation - xDestination;
double dy = yLocation - yDestination;
double dist = Math.sqrt(dx * dx + dy * dy);
return dist;
}
public double timeToDestination()
{
double distToTravel = distanceToDestination();
double time = distToTravel / maxSpeed;
return time;
}
}
- Suppose we rewrite setLocation as follows:
// WRONG!!
public void setLocation(double x, double y)
{
double xLocation = x;
double yLocation = y;
}
- Each time introduce braces, get a new "context"
- scope: area where data is visible
- within methods, scope is from point of declaration to end of
enclosing block
- cannot declare variable twice with same scope - illegal:
public double dist()
{
double d = xLocation - xDestination;
double d = yLocation - yDestination;
...
}
but could write something like
public double dist()
{
if ( xLocation > yLocation )
{
double d = xLocation - xDestination;
...
}
else
{
double d = yLocation - yDestination;
...
}
}
- Variables within a method are said to be local
- Parameters are effectively declared from the beginning of the method
to the end
- Can return from anywhere in a method:
public double timeToDestination()
{
if ( maxSpeed < 1e-4 )
{
// force VERY long time to get there
return distToTravel / 1e-30;
}
double distToTravel = distanceToDestination();
double time = distToTravel / maxSpeed;
return time;
}