0

I have a class named 'GameMap' which holds a private char[][] named 'map'. I created some utility functions to access/modify this 'map' from outside the class, for example: "setCharAt" that takes int x, int y, char c and does map[y][x] = c. I have another class called 'BotPlayer' which also holds a private char[][] named 'memorizedMap'. I want to use utility functions for this char[][] as well but I do not want to redeclare them inside 'BotPlayer'. I want to be able to call these functions in other classes and I want to be able to access the char[][] array directly inside these classes. For example:

GameMap map = new GameMap();
map.setCharAt(x,y,c);

Also, I do not want BotPlayer extending a parent Map class because it already extends another class.

What is the best practice to approach this?

1 Answer 1

2

Option 1: Use default method in interface

public interface IMap
{
    default void setCharAt(int x, int y, int c)
    {
        // logic here
    }
}

Then you can just implement the interface in your classes

Option 2: Use abstract class and interface

  1. Declare an interface with your common method for the map
  2. Create an abstract class that implement the interface
  3. In your classes, extend the abstract class

More info on abstract class: Abstract Methods and Classes

More info on interface with default method: Default Methods

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.