0

I am trying out the extends keyword in java, like this:

Account Class:

public class Account {
     public Account(...) {
         //Code...
     }
}

GameAccount Class:

public class GameAccount extends Account {
     public GameAccount(...) {
         //Code...
     }
}

But on Eclipse I get a nasty-looking error that says:

Implicit super constructor Account() is undefined. Must explicitly invoke another constructor.

How do I solve this?

TheCoffeeCup
  • 316
  • 5
  • 16
  • It just doesn't know how it should construct the `Account` part of a `GameAccount` object. Or, in other words, when you create a GameAccount, you need to (as the first part of the GameAccount constructor) call one of the Account constructors. Problem is, the compiler doesn't know which constructor to use, and it also doesn't know what the arguments should be for the constructor it uses. So the compiler has complained. – Parthian Shot Jul 23 '14 at 21:39

4 Answers4

4

You should call the constructor of Account from the first line of the constructor of GameAccount. If you don't do it, it tries to call the default (no parameters) constructor, and if it doesn't exist, you get this compilation error.

public class GameAccount extends Account {
     public GameAccount(...) {
         super (...);
         ...
     }
}

The alternative is to define a constructor that takes no parameters in Account :

public class Account {
     public Account() {
         //Code...
     }
     public Account(...) {
         //Code...
     }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
1

This should solve your problem:

public class GameAccount extends Account {
     public GameAccount(...) {
         super(...parameters that Account expects...);
         //Code...
     }
}
Shlublu
  • 10,917
  • 4
  • 51
  • 70
1
super(...)

within GameAccount's constructor referring to a new Account(...)

John
  • 816
  • 5
  • 17
1

You have to invoke a Superclass constructor in you subclasses' constructor as the first call:

public GameAccount(String game, int balance) {
    super(balance);
    // Other stuff
}
AlexR
  • 2,412
  • 16
  • 26