Java subclass no arguments

I have a class called “Card”

public class Card
{
  private int cardNumber;
  private String cardName;

  public Card(int cardNumber, String cardName)
  {
     this.cardNumber = cardNumber;
     this.cardName   = cardName;
  }

  public String toString()
  {
     return cardName;
  }

  public int getNumber()
  {
     return cardNumber;
  }
}

I’m trying to make a subclass of the Card class called “Ace”, but I keep getting the following error whenever I try to compile Ace: Ace.java:5: error: constructor Card in class Card cannot be applied to given types;

Here’s what I have for Ace:

public class Ace extends Card
{
   public String isAce;
   public Ace()
   {
   }

   public Ace(int cardNumber, String cardName, String isAce)
   {
      this.cardNumber = cardNumber;
      this.cardName = cardName;
      this.isAce = "yes";
   }
}

I don’t understand why I am getting the error when I try to compile Ace. What am I doing wrong?

Answer

Card has a constructor (so it doesn’t get a default empty constructor). You need to explicitly invoke it in the Ace constructor. Like,

public Ace(int cardNumber, String cardName, String isAce)
{
    super(cardNumber, cardName);
    this.isAce = "yes";
}

Without an explicit invocation of super() (or this()) the compiler implicitly adds super() (with no arguments). That doesn’t work here. Because (as I mentioned) Card already has a non-empty, non-default constructor.

Leave a Reply

Your email address will not be published. Required fields are marked *