Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

class - Problem with get methods not having required arguments

public class Card
{


private int rank;
private int suit;
public Card(int r,int s){
   
   rank=r;
   suit=s;
   
}
public Card getRank(Card r)
{
    return r;
    
}
public Card getSuit(Card s)
{
    
    return  s;
}
}

private static String toImage(Card card)
{
    return "" + card.getRank() + "cdhs".charAt(card.getSuit()) + ".gif";
}
}

The first code is the Card class where I am trying to make getter methods that return rank and suit. The second code is a class that needs to use the get methods but it says "method getSuit/getRank cannot be applied to given types. Required: Card Found :no arguments reason: actual and formal argument lists differ in length"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is useful to consider that instance methods are intended to work with an instance of the class on which the are defined. If this is not intuitive, it can be helpful to use the keyword this to emphasize this fact until you get used to it.

For example, your method

public Card getRank(Card r)
{
    return r;

}

makes little sense in an object-oriented environment. What you are intending to do is retrieve the rank from the Card instance, so there isn't any reason to pass another Card instance as an argument. The use of this emphasizes the correct way to write this method:

public class Card
{
    private final int rank;
    private final int suit;

    public Card(int r,int s)
    {
        this.rank=r;
        this.suit=s;
    }

    public int getRank()
    {
        return this.rank;
    }
    :
    :
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...