Settlers (Methods)
Eventually the marauders, taken with the rich soil and natural resources of Britain, became settlers. Stronger militarily than the Romanized Britons it was possible for the invaders to push the Britons further and further west. As they pushed the native people out of their lands the Anglo-Saxons and Jutes became the new inhabitants of a large section of Britain.
The new settlers built carts to carry their farm goods to market. Therefore, you can make a class file to declare fields that are common to wagons.
Here is the code for a class that establishes fields for an ancient farmer's cart. The display code at the bottom of the file establishes a method. The method tells Java what to do if the method is called from the calling class.
- import static java.lang.System.out;
- public class SaxonCart {
- //The double variable type allows the system to
- //work with decimal numbers.
- String cartname;
- int wheelsize;
- double avgspeed;
- /* A method is a list of instructions
- * that you want the computer to process.
- * An advantage of an Object Oriented
- * programming language like Java is
- * that the defining class can perform
- * tasks using the data passed from the
- * calling class.
- */
- public void display() {
- out.println();
- out.println("Cartname: " + cartname);
- out.println("Wheel Size: " + wheelsize);
- out.println("Average Speed: " + avgspeed);
- }
- //The above display code is a method that can be
- //called by the calling class
- }
Here is the code for the calling class. Notice how the UseSaxonCart class communicates with the SaxonCart class. Two objects are created: annaSaxonCart and cenaSaxonCart. The annaSaxonCart.display(); and the cenaSaxonCart.display(); lines call the display method from the SaxonCart class.
- import static java.lang.System.out;
- public class UseSaxonCart {
- public static void main(String[] args) {
- //SaxonCart saves a space in memory for an object. annaSaxonCart = new SaxonCart actually creates the object.
- SaxonCart annaSaxonCart = new SaxonCart();
- SaxonCart cenaSaxonCart = new SaxonCart();
- annaSaxonCart.cartname = "Anna's Little Cart";
- annaSaxonCart.wheelsize = 3;
- annaSaxonCart.avgspeed = .4;
- cenaSaxonCart.cartname = "Cena's Big Monster Cart";
- cenaSaxonCart.wheelsize = 5;
- cenaSaxonCart.avgspeed = .6;
- annaSaxonCart.display();
- cenaSaxonCart.display();
- }
- }
Use Save As to save the code to your folder as: SaxonCart.java. Then compile the code in the Command prompt window. Use javac SaxonCart.java to create the .class file. Then use the same process to save the code of the UseSaxonCart.java file. Use java UseSaxonCart to run the program.
Your output should look like this:
c:\javamike>java UseSaxonCart
Cartname: Anna's Little Cart
Wheel Size: 3
Average Speed: 0.4
Cartname: Cena's Big Monster Cart
Wheel Size: 5
Average Speed: 0.6