qwertz
qwertz

Reputation: 325

Use methods from class one in a method in class two

I've got an assignment (written in java) that is very specific in terms of interfaces and how and where to implement all sorts of stuff. And I know that alot of similiar questions have been asked but I can't seem to connect them with my problem.

The class i have to implement is

 public class Algorithm<G extends Game<M>, M extends Move>
implements AIp<M>

I am not allowed to change that name. The method in this class has to implement a few methods from the class G.

The interface Game which is implemented in G contains a few methods like makeMove() or evaluateSituation() (We are playing Connect four here).

I've implemented all the methods from both Interfaces in seperate classes so far and I also created a playing Board (class). In G I created a board object on which the game is played.

So my questions is: how do I use the methods from the class G and the class Board in my method (in Algorithm) without creating a new object of Board (cause I already have that) and/or G.

Edit:

public class Algorithm<G extends Game<M>, M extends Move> implements AIp<M> {

    G g;

    public Algorithm(G g) {
        this.g = g;
    }

    public someMethod() {
         g.getBoard().someMethodFromBoard();
         // The line above gives the following error:
         // The method getBoard() is undefined for the type G.
         // 1 quick fix available: Add cast to 'g'.
    }


}


        public class G {
             public Board getBoard() {
                 return somelist;
             }
}

someList isn't implemented in Game.

Upvotes: 0

Views: 106

Answers (1)

Tuan Pham
Tuan Pham

Reputation: 1110

As far as I understand your concept I think you can simply declare getter method for Board object in Game class and implement it in G.

class G 
{
...
    public Board getBoard() 
    {
        return theBoardYouCreatedInG;
    }    
}

If you already have G object then just provide it in the constructor of Algorithm. Then you just use the G object and its getter method to get Board object

public class Algorithm<G extends Game<M>, M extends Move> implements AIp<M>
{

    G g;

    public Algorithm(G g) 
    {
        this.g = g;
    }

    public someMethod()
    {
         g.someMethodFromG();
         g.getBoard().someMethodFromBoard();
    }


}

EDIT: If you want to use your code this way, you need getBoard() implemented in Game. If that's not possible then I guess you will have to provide Board object in the constructor (like you did with G object)

And G is not supposed to be a real class, it's a type parameter for some class that you will specify later (in this case, any class that implements Game), if you want to use methods of G they need to be declared in Game.

Upvotes: 1

Related Questions