0

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

Koborl
  • 235
  • 1
  • 11
  • Without knowing more about the problem and the context, I do not think there's a good answer to this question. – plalx Sep 14 '13 at 23:54
  • You can't use inheritance *at all*, or between the two classes? Between the two classes makes sense, since they're not really "related" to one another. – Makoto Sep 14 '13 at 23:56
  • Well basically I have two classes that are essentially identical and it feels extremely wasteful to be retyping the same code for both classes (they both use exactly the same methods). Is there another way to handle this. – Koborl Sep 14 '13 at 23:59
  • Yes. Inheritance. Can you use it? – Makoto Sep 15 '13 at 00:01
  • No, i've been told specifically for this not to use it at all. – Koborl Sep 15 '13 at 00:05

3 Answers3

1

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.

windwarrior
  • 456
  • 2
  • 11
1

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

Deryck
  • 7,608
  • 2
  • 24
  • 43
0

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.

Bernhard Barker
  • 54,589
  • 14
  • 104
  • 138