I need to call and instance of the class ControlledTank
to access the GetPlayer
method which I will complete later. However, when I try to create an instance it's using the constructor not the class.
public class ControlledTank
{
private float Tangle;
public ControlledTank(Player player, int tankX, int tankY, Game game)
{
Tangle = 0;
//throw new NotImplementedException();
}
public Player GetPlayer()
{
throw new NotImplementedException();
}
}
I don't have the values to parse into the constructor either so I just get errors.
The result I get
4 Answers 4
Your constructor expects 4 parameters:
public ControlledTank(Player player, int tankX, int tankY, Game game)
{
//...
}
You're passing it 0 parameters:
new ControlledTank()
Hence the error. So you have two options. Either pass the parameters needed by the constructor, or also add a constructor with the parameters (or lack thereof) which you need. For example:
public ControlledTank()
{
Tangle = 0;
}
Note: A class can have multiple constructors. A class can also have a default constructor with 0 parameters (and no internal logic), but only if no other constructor is specified.
Comments
The error is right in front of you, you can't pass no parameters to constructor that must have parameters. Here is your options, you can decide what you want according to task in front of you:
Add default constructor:
public ControlledTank(){}
or make your constructor parameters with default values:
public ControlledTank(Player player = null, int tankX = 0, int tankY = 0, Game game = null){}
"it's using the constructor not the class" makes no sense. If you want to call constructor when you are accessing class by putting .
operator after class name, you need to have static constructor (they are always parameterless):
static ControlledTank() {}
But it's useful, when you are want to initialize some static fields in it.
2 Comments
A constructor expects parameters to construct the class, and you're not providing parameters.
To fix this, you just need an empty default constructor:
public ControlledTank(){}
Comments
You need to write an empty constructor as well if you need to use it like this. The constructor is used to build the instance of the class:
public ControlledTank()
{
Tangle = 0;
player = new Player();
tankX = 0;
tankY = 0;
game = new Game();
}
Comments
Explore related questions
See similar questions with these tags.
GetPlayer
static?"it's using the constructor not the class"
- What does that even mean? What were you expecting to happen? Why? A constructor is used to construct an instance of a class. Your constructor expects parameters. You are not supplying those parameters. Hence the error.