Vikings (Accessors)
The Anglo-Saxons continued to spread in all directions and became the dominant force in Britain. However, in the late 700's new invaders landed on Britain's shores. The Vikings (marauders from the North) came to pillage the people of Britain. Like the Anglo-Saxons they too became settlers.
You can add accessors to make your code more secure. Instead of making your variables directly accessible to other classes, you add setter methods and getter methods to transfer data.
Here is the code for a class that establishes fields for a Viking ship. Setter and getter methods are presented for two fields.
- import static java.lang.System.out;
- public class VikingShip {
- // The word private is a keyword and prevents any other
- // class from directly accessing the variable.
- private String name;
- private int sail;
- private double hullwidth;
- /* The setShipName method is called
- * a setter method. The setter establishes
- * that shipname and n share the same value.
- * public is a keyword that does allow access
- * from other classes.
- */
- public void setName(String n) {
- name = n;
- }
- /* The getShipName method is called
- * a getter method. The getter returns
- * the value of shipname.
- */
- public String getName() {
- return name;
- }
- public void setSail(int s) {
- sail = s;
- }
- public int getSail() {
- return sail;
- }
Here is the code for the calling class. Notice the setter and getter methods.
- import static java.lang.System.out;
- public class UseVikingShip {
- public static void main(String[] args) {
- VikingShip thorVikingShip = new VikingShip();
- VikingShip ingridVikingShip = new VikingShip();
- thorVikingShip.setName("Thor's Revenge");
- thorVikingShip.setSail(40);
- ingridVikingShip.setName("Ingrid's Invader");
- ingridVikingShip.setSail(50);
- out.println();
- out.println("Thor's ship is called " + thorVikingShip.getName());
- out.println("and the ship's sail size in square feet is " + thorVikingShip.getSail());
- out.println();
- out.println("Ingrid's ship is called " + ingridVikingShip.getName());
- out.println("and the ship's sail size in square feet is " + ingridVikingShip.getSail());
- }
- }
Use Save As to save the code to your folder as: VikingShip.java. Then compile the code in the Command prompt window. Use javac VikingShip.java to create the .class file. Then use the same process to save the code of the UseVikingShip.java file. Use java UseVikingShip to run the program.
Your output should look like this:
c:\javamike>java UseVikingShip
Thor's ship is called Thor's Revenge
and the ship's sail size in square feet is 40
Ingrid's ship is called Ingrid's Invader
and the ship's sail size in square feet is 50