Vikings (Accessors)

Viking ship

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.

  1. import static java.lang.System.out;
  2. public class VikingShip {
  3. // The word private is a keyword and prevents any other
  4. // class from directly accessing the variable.
  5. private String name;
  6. private int sail;
  7. private double hullwidth;
  8. /* The setShipName method is called
  9. * a setter method. The setter establishes
  10. * that shipname and n share the same value.
  11. * public is a keyword that does allow access
  12. * from other classes.
  13. */
  14. public void setName(String n) {
  15. name = n;
  16. }
  17. /* The getShipName method is called
  18. * a getter method. The getter returns
  19. * the value of shipname.
  20. */
  21. public String getName() {
  22. return name;
  23. }
  24. public void setSail(int s) {
  25. sail = s;
  26. }
  27. public int getSail() {
  28. return sail;
  29. }

Java code

Here is the code for the calling class. Notice the setter and getter methods.

  1. import static java.lang.System.out;
  2. public class UseVikingShip {
  3. public static void main(String[] args) {
  4. VikingShip thorVikingShip = new VikingShip();
  5. VikingShip ingridVikingShip = new VikingShip();
  6. thorVikingShip.setName("Thor's Revenge");
  7. thorVikingShip.setSail(40);
  8. ingridVikingShip.setName("Ingrid's Invader");
  9. ingridVikingShip.setSail(50);
  10. out.println();
  11. out.println("Thor's ship is called " + thorVikingShip.getName());
  12. out.println("and the ship's sail size in square feet is " + thorVikingShip.getSail());
  13. out.println();
  14. out.println("Ingrid's ship is called " + ingridVikingShip.getName());
  15. out.println("and the ship's sail size in square feet is " + ingridVikingShip.getSail());
  16. }
  17. }


Java code

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

 

< Parameters Viking Settlers (Subclasses) >