Frage

I have two classes Boat and Mines, which have exactly the same methods and variables.

the only difference is that they are Initialized in different positions.

for Boat

xPosition = 3 yPosition = 4

for Mine

xPosition = 1 yPosition = 1

I've been told specifically not to use inheritance for this, what else could I use to improve the design

War es hilfreich?

Lösung 3

If they only differ in the values of their members, inheritance seems somewhat pointless in any case. But having 2 unrelated classes would be worse.

How about something like this?

class SomeClass
{
   int xPosition, yPosition;
   enum Type
   {
      Boat, Mine
   }
   public SomeClass(Type type)
   {
      if (type == Type.Boat)
      {
         xPosition = 3;
         yPosition = 4;
      }
      else
      {
         xPosition = 1;
         yPosition = 1;
      }
      // assign 'type' to a class variable here if required
   }
}

Construct using:

new SomeClass(SomeClass.Type.Boat)

or:

new SomeClass(SomeClass.Type.Mine)

You may want to pick a better name than SomeClass.

Andere Tipps

You could give both of them some sort of location class, give that class the X and Y positions, and make it a property of both the mine and the boat. Sad thing you'll need getters/setters for the location class nevertheless.

The idea of object-oriented programming is for this exact reason.

Boat and Mine should not be classes, they should be new objects made from another class (we'll call it - waterStuff).

class waterStuff {
    public xPosition;
    public yPosition;
}

... then somewhere in the code you set them to new objects. I don't use Java so I'll do it as close as I can: (these would probably be inside another class using the waterStuff as a namespace for reference)

Boat = new waterStuff;
Mine = new waterStuff;

Boat->xPosition = 3;
Boat->yPosition = 4;
Mine->xPosition = 1;
Mine->yPosition = 1;

I wish I could be more java-specific but hopefully this gets you on the right track.

EDIT: Don't you just love CS101

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top