mathsymaths
mathsymaths

Reputation: 31

How to avoid redeclaring functions in multiple classes in Java?

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?

Upvotes: 0

Views: 45

Answers (1)

Hunter Tran
Hunter Tran

Reputation: 15245

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

Upvotes: 2

Related Questions