Home > front end >  Calling object within object?
Calling object within object?

Time:11-01

I am taking a Java class and the teacher isn't being very helpful with my question. The assignment is to create a hand of cards using the following tester class:

public class Tester
{
    public static void main(String[] args)
    {
        // No pair
        System.out.println("No pair");
        Hand noPair1 = new Hand(new Card(10, 3), new Card(3, 0), new Card(13, 2), new Card(5, 1), new Card(14, 3));
        System.out.println("\n");
    }
}

There is a Hand class and a Card class:

public class Hand
{
    private ArrayList<Card> cards;
 
    public Hand()
    {
        cards = new ArrayList<Card>(); // initialize cards
    }
}

Card Class:

public class Card
{
    
    // instance variables
    private final int rank; // card rank
    private final int suit; // card suit

    public Card(int rankIn, int suitIn)
    {
        rank = rankIn;
        suit = suitIn;
    }

My question: How do I get the Hand class to call the Card class from within the Hand class? The error is occurring on the line Hand noPair1 = new Hand(new Card(10,3), ...);

I am not allowed to change the Tester class.

Tried compiling and running the Tester class.

CodePudding user response:

    public Hand()
    {
        cards = new ArrayList<Card>(); // initialize cards
    }

You only have the one constructor for Hand, but it's not a constructor that takes Cards.

You will need to add a constructor, or a method, to Hand that accepts some Cards.

CodePudding user response:

when you call new Hand(...) you are calling a constructor of the Hand class. By the looks of it the only constructor for hand is a zero-arguments constructor. Namely, this one:

public Hand()
{
    cards = new ArrayList<Card>(); // initialize cards
}

There is no constructor for Hand that takes in a multiple cards as

Hand noPair1 = new Hand(new Card(10,3), ...)

would necessitate.

You have a couple options:

  1. Add a new constructor to Hand that takes in a single Card (or using varargs, multiple Cards). This would make the above snippet valid.

  2. Make the Hand's cards feild public, create a Hand instance with the existing zero-args constructor, and then add the cards to the cards feild after creating the hand.

Both of these have their advantages and disadvantages and there are of course many more ways to solve this - but those two are probably the simplest. If you cannot edit the test file, the first with varargs seems like your only option.

  • Related