简体   繁体   中英

Java: How to use the toString() method of one class in an other one?

I'm working on this project while learning Java, I created a Card class that has a toString() method but when I'm trying to convert a Card object to a String in the Deck class I'm getting an error .

Here is the Card class:

private final Rank cardRank;
private final Suit cardSuit;

public Card(Rank cardRank, Suit cardSuit){
    this.cardRank = cardRank;
    this.cardSuit = cardSuit;
}

public String toString(){
    return "The " + cardRank + " of " + cardSuit;
}

Here is the Deck class:

private Card[] card = new Card[52];

public Deck(){
    int i = 0;
    for(Suit suit: Suit.values()){
        for(Rank rank: Rank.values()){
            card[i++] = (new Card(rank, suit));
        }
    }
}

public String toString(int i){
    return card[i];
}    

You can't cast a Card object into String object.

You can get the String representation of the Card object through toString() method.

Try like below

public String toString(int i){
    return card[i].toString();
} 

Calling return card[i] returns an object of type card. You have to actually call the toString() method so that your return object is a String and not a Card. Hope this helps!

If the toString() of each of your class does not have the @Override annotation, then you have to explicitly call the toString() .

Example:

return card[i].toString();
return "The " + cardRank.toString() + " of " + cardSuit.toString;

If you add the @Override annotation like this:

@Override
public String toString(){
    return "The " + cardRank.toString() + " of " + cardSuit.toString();
}

Then the Deck class toString(int i) can look like:

public String toString(int i){
    return card[i];
} 

If you add the @Override to the Rank and Suit class, then the Card class toString() can look like:

public String toString(){
    return "The " + cardRank + " of " + cardSuit;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM