Flow control: access

Dr Andy Evans

[Fullscreen]

Encapsulation

  • The variable passing in methods is set up so you don't need to know what other people have called the variable in their classes to use them.
    
    System.out.println(someString);
    
    
  • You don't need to know the variable the someString value is placed in - the label is just added inside System.out.
  • This is another key element of encapsulation: you don't need to know what goes on inside classes you use.

Accessors and Mutators

  • You can refer to object's variables directly...
    	
    Point p1 = new Point()
    p1.x = 10.0;
    
    
  • However, it is good practice to use a method to get and set other object's variables...
    	
    pt1.setX (10.0);
    double x1 = pt1.getX();
    
    

Accessor Methods

  • Get a variable from an Object
	
// main class
Point pt1 = new Point();



double x1 = pt1.getX();


 





 
<-



 
	
// Point

double x = 20.0;

double getX () {  	    
    return x;
}

 

Mutator Methods

  • Set a variable in an object
	
// main class
Point p1 = new Point();


p1.setX(222.2);



 




 
->




 
	
// Point


double x = 0.0;
void setX (double xIn) {
    x = xIn;
}

 

Together

	
public class Point {

    double x = 0.0;

    void setX (double xIn) {
		x = xIn;
    }

    double getX() {
		return x;
    }

}


Scope

	
public class Point {

    double x = 0.0;				<-- Instance variable

    void setX (double xIn) {	<-- Parameter variable
		x = xIn;
    }

    double getX() {
		return x;
    }

    void someMethod () {
		double a = 10.0;		<-- Method variable
    }
	
}


this keyword

  • What if you use the same name?
	
public class Point{
    double x = 200.0;	

    void setX (double x) {
		this.x = x;
    }
}

Access

  • It's fine for encapsulation to demand accessors and mutators, but how do we enforce it?
  • Access modifier keywords:
    • public : usable by anyone;
    • protected : usable by classes that inherit;
    • private : only useable by the object.
  • Default is code can be seen only in same directory (package - which we'll come back to).

Variable access

	
public class Point {

    private double x = 0.0;

    public void setX (double xIn) {
		x = xIn;
    }

    public double getX() {
		return x;
    }

}

Variable access

  • If variables are declare final they can't be altered.
  • Such variables are known as 'constants' in other languages.
  • Conventionally in uppercase and underscores, e.g.:

// 10 year dollar average per kilo
final int PRICE_OF_GOLD = 10100;
final int PRICE_OF_SILVER = 202;
final int PRICE_OF_BEER = 4;

Review

  • Get used to assuming any variable you want another class to interact with has 'set' and 'get' mutator and accessor methods.
  • Always make these public (or protected) and the variables private.