0

I am trying to instantiate an object (created in a "EmptySea" subclass of "Ship" class) into another "Ocean" class to fill an array with "EmptySea" objects.

Error is "EmptySea cannot be resolved to a type."

Here is my Ocean class code:

public class Ocean {

    // Instance variables.
    public Ship[][] ships = new Ship[10][10];
    public int shotsFired;
    public int hitCount;

    // Constructor.
    public Ocean() {
        shotsFired = 0;
        hitCount = 0;
        for (int row = 0; row < ships.length; row++) {
            for (int column = 0; column < ships[row].length; column++) {
                ships[row][column] = new EmptySea();

public abstract class Ship {

    // Instance variables.
    private int bowRow;
    private int bowColumn;
    private int length;
    private boolean horizontal;
    private boolean[] hit = new boolean[4];

    // No constructor needed for Ship class.

    // Methods (too many to show).

    public class EmptySea extends Ship {

        // Constructor.
        EmptySea() {
            length = 1;
        }

        // Inherited methods to define.
        int getLength() {
            return length = 1;
        }

        String getShipType() {
            return "Empty";
        }

        @Override
        boolean shootAt(int row, int column) {
            return false;
        }

        @Override
        boolean isSunk() {
            return false;
        }

        @Override
        public String toString() {
            return "-";
        }
    }

The ships array has been properly declared as an instance variable in Ocean class. Basically, it is not letting me put the EmptySea() object (the code for the "Ship" class and its "EmptySea" subclass runs correctly).

Do I need to somehow reference the superclass in this case?

If there's an easier way to do it, I can't do it that way (this way is specified in assignment).

Adrian Colomitchi
  • 3,974
  • 1
  • 14
  • 23
  • Comments are not for extended discussion; this conversation has been [moved to chat](http://chat.stackoverflow.com/rooms/130016/discussion-on-question-by-broncosaurus-java-accessing-a-subclass-constructor-i). – Bhargav Rao Dec 07 '16 at 12:56

1 Answers1

0

Learn about the difference between a static nested class and an instance nested class.

Some other SO question on the same.

Short term: declare your inner EmptySea class with static, then read/understand why - in brief, without static an EmptySea instance cannot be created outside the context of a Ship instance.

Community
  • 1
  • 1
Adrian Colomitchi
  • 3,974
  • 1
  • 14
  • 23