Java

OOP GUIDE / WORK

 

SPACESHIP CLASS

 

Topics

  • Data Encapsulation
  • toString()

 

 

TASK – PART 1 – SETUP

 

Copy and paste the following Spaceship class into your IDE.

 

public class Spaceship

{

    public int hp;

    public double size;
    public String name;

 

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

        hp = tHp;

        size = tSize;

        name = tName;

    }

}

 

 

 

TASK – PART 2 – DATA ENCAPSULATION

 

A) Use data encapsulation for the class above.

  • Make the data fields (instance variables) private.
  • Add get methods for all three data fields.
  • Add set methods for all three data fields.  However, for hp and size, the set method should only work if the value is positive, otherwise it will do nothing.  Similarly, for name, the set method should only work if the String is not empty.

 

B) Add a toString() method to Spaceship.  It returns a string with the ship’s name and hp formatted as such:

         
Enterprise (10hp)

 

 

TASK – PART 3 – TESTING YOUR SPACESHIP CLASS

 

Inside the main function of a SpaceshipTester class, create a Spaceship object and test all of the methods in the class.