Turtle Simulation Program with Java Classes
Learn how to create Turtle objects and Worlds, set properties, and call methods in Java classes. Implement and compile the classes to simulate turtle movements.
Turtle Simulation Program with Java Classes
E N D
Presentation Transcript
Turtle =========== xPos: int yPos: int direction: double bodyColor: Color name: String .... ---------------------- forward(int): void backwark(int):void setName(String) ..... World ============ width: int height: int background:Color ... ------------------------ newColor(Color) ... 1. Ett problem/uppgift 2. Beskriv de typer av objekt som finns i klassdiagram. Klassdiagrammet har (liksom klassen) två huvuddelar: - instansvariabler med typ - metoder med parameterlista och returtyp
public class Turtle { private int xPost; private int yPos private double direction; private Color bodycolor private String name; public Turtle(World w) { .... } public setName(String newName) { name = newName; } ..... } public class World { private int height; private int width; private Color background; public World(int w, int h) { .... } public setColor(Color newC) { background = newC; } ..... } 3. Implementera (koda) klasserna. Spara i filer, t ex Turtle.java
public class Turtle { private int xPost; private int yPos private double direction; .... public Turtle(World w) { .... public setName(String n) { name = n; } ..... } public class World { private int height; private int width; private Color background; ... public World(int w, int h) { .... } public setColor(Color newC) { background = newC; } .... } . World w = new World(400,400); Turtle t1 = new Turtle(w); Turtle t2 = new Turtle(w); Turtle t3 = new Turtle(w); t1.turn(90); t1.forward(100); t2.forward(70); 4. MEN: vi måste skapa objekt och anropa metoder, annars händer inget {
public class Turtle { private int xPost; private int yPos private double direction; .... public Turtle(World w) { .... } ..... } public class World { private int height; private int width; private Color background; ... public World(int w, int h) { .... } .... } public class TurtleTest { public static void main(String[] arg) { World w = new World(400,400); Turtle t1 = new Turtle(w); Turtle t2 = new Turtle(w); Turtle t3 = new Turtle(w); t1.turn(90); t1.forward(100); t2.forward(70); } } 5.Satserna skall ligga i en speciell metod som skall heta main. Lägg main-metoden i en egen klass, T ex TurtleTest. 6. Kompilera alla klasserna => - kompilatorn testar om syntaxen är korrekt - Sen översätts koden till java- Bytekod (class-filer)
7. Nu kan vi köra filen som innehåller main-metoden. > run TurtleTest