Java

OOP GUIDE / WORK

 

SPACESHIP CLASS SOLUTIONS

 

 

TASK – PART 1 – SETUP

 

No solution required

 

 

TASK – PART 2 – DATA ENCAPSULATION

 

Here is my solution:

 

public class Spaceship

{

     private int hp;

     private double size;

     private String name;

 

     public Spaceship(int tHp, double tSize, String tName)

     {

           hp = tHp;

           size = tSize;

           name = tName;

     }

 

     public int getHp()

     {

           return hp;

     }

 

     public double getSize()

     {

           return size;

     }

 

     public String getName()

     {

           return name;

     }

 

     public void setHp(int tHp)

     {

           if (tHp > 0)

           {

                hp = tHp;

           }

     }

 

     public void setSize(double tSize)

     {

           if (tSize > 0)

           {

                size = tSize;

           }

     }

 

     public void setName(String tName)

     {

           if (!tName.equals(""))

           {

                name = tName;

           }

     }

 

     public String toString()

     {

           return name + "(" + hp + "hp)";

     }

}

 

 

 

TASK – PART 3 – TESTING YOUR SPACESHIP CLASS

 

Here is my solution but not that your solution could be fairly different:

 

public class SpaceshipTester

{

     public static void main(String[] args)

     {

           Spaceship ent = new Spaceship(10, 2400.5, "Enterprise");

          

           //Testing get methods

           System.out.println(ent.getHp());

           System.out.println(ent.getSize());

           System.out.println(ent.getName());

          

           //Testing set methods

           System.out.println(ent);  //calling toString()

          

           ent.setHp(17);

           System.out.println(ent);

           ent.setHp(-3);            //does nothing

           System.out.println(ent);

          

           ent.setSize(4444.4);

           System.out.println(ent.getSize());

           ent.setSize(-2345.2);     //does nothing

           System.out.println(ent.getSize());

          

           ent.setName("Millenium Falcon");

           System.out.println(ent);

           ent.setName("");          //does nothing

           System.out.println(ent);

     }

}