Delete
Delete

Reputation: 299

Access an Object in Another Class from an Interface?

Is this even possible? Here is the important parts of the code I am currently working with:

public class Bag : IBag
{
    public IRack NewRack() { ...some code here...}
}

public class Rack : IRack
{
   public void SwapAllTiles() { ...can I access the Bag object here somehow?... }
} 

My question is, can I access the current Bag object in the Rack class without deriving from the Bag class, like through the IRack interface somehow? The way I have it working right now is I have Rack derive from Bag and I can use a getter to access the current bag's instance, but this doesn't seem like good form. Would using a static instance be better?

NOTE: I don't want to put a private Bag object in my Rack class, there are technically separate (its basically a scrabble tile bag and a scrabble rack. I need the rack to be able to reference or access the bag for the tiles within it but I do not want each rack to have its own bag.)

Upvotes: 1

Views: 79

Answers (1)

Robert Harvey
Robert Harvey

Reputation: 180787

Pass your Bag object in as a parameter to a method in your Rack object.

You don't have to hold a reference to it in a member variable if you don't want to. But if you want persistent access to it, you do need a private member. Without a private member reference, you'll only be able to access it for the lifetime of your method.

public class Rack : IRack
{
   public void SwapAllTiles(IBag bag) { ...Now you can access it... }
}

Upvotes: 2

Related Questions