************************ Ship.java A Ship class illustrating object-oriented programming concepts. Incorporates Javadoc comments. See ShipTest.java for a test. ************************ /** Ship example to demonstrate OOP in Java. * * @author * Larry Brown * @version 2.0 */ public class Ship { // Instance variables private double x=0.0, y=0.0, speed=1.0, direction=0.0; private String name; // Constructors /** Build a ship with specified parameters. */ public Ship(double x, double y, double speed, double direction, String name) { setX(x); setY(y); setSpeed(speed); setDirection(direction); setName(name); } /** Build a ship with default values * (x=0, y=0, speed=1.0, direction=0.0). */ public Ship(String name) { setName(name); } /** Move ship one step at current speed/direction. */ public void move() { moveInternal(1); } /** Move N steps. */ public void move(int steps) { moveInternal(steps); } private void moveInternal(int steps) { double angle = degreesToRadians(direction); x = x + (double)steps * speed * Math.cos(angle); y = y + (double)steps * speed * Math.sin(angle); } private double degreesToRadians(double degrees) { return(degrees * Math.PI / 180.0); } /** Report location to standard output. */ public void printLocation() { System.out.println(getName() + " is at (" + getX() + "," + getY() + ")."); } /** Get current X location. */ public double getX() { return(x); } /** Set current X location. */ public void setX(double x) { this.x = x; } /** Get current Y location. */ public double getY() { return(y); } /** Set current Y location. */ public void setY(double y) { this.y = y; } /** Get current speed. */ public double getSpeed() { return(speed); } /** Set current speed. */ public void setSpeed(double speed) { this.speed = speed; } /** Get current heading (0=East, 90=North, 180=West, * 270=South). I.e., uses standard math angles, not * nautical system where 0=North, 90=East, etc. */ public double getDirection() { return(direction); } /** Set current direction (0=East, 90=North, 180=West, * 270=South). I.e., uses standard math angles,not * nautical system where 0=North,90=East, etc. */ public void setDirection(double direction) { this.direction = direction; } /** Get Ship's name. Can't be modified by user. */ public String getName() { return(name); } private void setName(String name) { this.name = name; } } ********************* ShipTest.java ********************* public class ShipTest { public static void main(String[] args) { Ship s1 = new Ship("Ship1"); Ship s2 = new Ship(0.0, 0.0, 2.0, 135.0, "Ship2"); s1.move(); s2.move(3); s1.printLocation(); s2.printLocation(); } }
Aug 29