3.9 The Actor Constructor
Writing a Constructor for a Greenfoot Actor
Unit 3: Methods, Worlds, and Constructors · Lesson 3.9 · about 30 minutes · no coding experience needed
Right now every enemy you create is identical. A constructor with a parameter is how you make a fast one, a slow one, and a boss, all from one class, in one line each.
What you will be able to do
- Write a constructor for an actor class
- Take a parameter and store it in an instance variable
- Create actors with different starting values
Words you will need
- Initialise
- In plain words Give something its starting value at birth.
- More precisely Assign an instance variable its initial value, usually in the constructor.
Build it step by step
Every step below leaves a scenario that compiles and runs. If you stop halfway you will have something that works, not something broken. Follow along in Greenfoot rather than reading straight through.
-
Step 1
On your screen An actor class with a constructor that takes a speed parameter.
public class Enemy extends Actor { private int speed; public Enemy(int enemySpeed) { speed = enemySpeed; } public void act() { move(speed); } }Everything here you have already met, assembled.
`private int speed;` is an instance variable from 3.8, declared with no starting value. `public Enemy(int enemySpeed)` is a constructor from 3.6 with a parameter from 3.3. `speed = enemySpeed;` copies the value the caller supplied into the instance variable, where it will survive.
That last line is the whole trick: the parameter dies when the constructor ends, so it has to be saved somewhere that lasts.
-
Step 2
On your screen Three enemies created with different speed values in prepare.
public void prepare() { addObject(new Enemy(1), 2, 2); // slow addObject(new Enemy(4), 8, 5); // fast addObject(new Enemy(7), 15, 9); // very fast }One class, three different enemies. The value goes in the parentheses of `new`, exactly like an argument to any other method, because a constructor IS a method that runs at creation.
Compare this with what you would need without a constructor: three classes, or a setter you have to remember to call on every single enemy.
-
Step 3
On your screen A constructor setting several instance variables at once.
private int speed; private int health; public Enemy(int enemySpeed, int startingHealth) { speed = enemySpeed; health = startingHealth; } addObject(new Enemy(3, 20), 5, 5);Two parameters, two instance variables. The pattern scales exactly as you would expect, and the arguments stay positional: speed first, health second, because that is the order the constructor declares.
Get them the wrong way round and you have a very slow enemy with three health and no error message at all.
-
Step 4
On your screen An actor class with both a no-argument and a parameterised constructor.
public Enemy() { speed = 2; // a sensible default } public Enemy(int enemySpeed) { speed = enemySpeed; }You can have both. `new Enemy()` gets the default; `new Enemy(5)` gets a chosen speed. Java picks by the arguments you supply.
Worth knowing because the moment you write a constructor WITH parameters, `new Enemy()` stops working unless you also keep a no-argument one. That surprises people, and the error is "constructor Enemy cannot be applied to given types".
Mistakes almost everyone makes here
These are the wrong ideas students actually build at this point. Read them even if you think you understand, because a wrong idea you have not noticed is the expensive kind.
Common wrong idea The parameter and the instance variable are the same thing.
What is actually true The parameter dies when the constructor ends. The assignment is what saves the value.
Why it matters Missing the assignment leaves the instance variable at zero, and every enemy stands still.
Common wrong idea An actor constructor needs super() like a world does.
What is actually true Usually not. Actor has a no-argument constructor Java calls for you.
Why it matters Adding a super call with arguments to an actor is a compiler error that confuses people who just learned super in 3.6.
Common wrong idea Adding a constructor with parameters leaves `new Enemy()` working.
What is actually true It stops working unless you also write a no-argument constructor.
Why it matters Every existing `new Enemy()` in prepare() breaks at once, which looks like the constructor broke the class.
Common wrong idea You can name the parameter the same as the instance variable and it just works.
What is actually true It compiles, but the parameter hides the field and the assignment does nothing useful.
Why it matters This course uses different names to avoid it entirely. The professional fix is `this`, which is beyond this course.
Check your understanding
Answer these before moving on. They are graded instantly and you can retry.
-
1. In a constructor `public Enemy(int enemySpeed)`, why is `speed = enemySpeed;` needed?
-
2. How do you create a fast enemy given `public Enemy(int enemySpeed)`?
-
3. You add `public Enemy(int speed)` to a class that had no constructor. What happens to existing `new Enemy()` calls?
-
4. Does an Actor subclass constructor normally need to call super?
Fill in the code
Give Coin a constructor so each coin can be worth a different number of points. Store the value where it will survive.
public class Coin extends Actor
{
private int value;
public (int coinValue)
{
= ;
}
}
Stuck? Open a hint for each blank
- Blank 1: A constructor is named after its class, exactly.
- Blank 2: The variable that survives after the constructor ends.
- Blank 3: The parameter holding what the caller supplied.
Lesson quiz
This one counts toward your progress. Take it when the section above makes sense.
-
1. An actor constructor runs:
-
2. Which creates an enemy with speed 3 and health 20, given `Enemy(int speed, int health)`?
-
3. What is the advantage of a constructor parameter over setting values afterward?
-
4. A constructor takes a parameter but never assigns it to an instance variable. What happens?
The short version
- An actor constructor has the class name, no return type, and runs once at creation.
- A parameter carries the value in; an assignment to an instance variable makes it last.
- Arguments go in the parentheses of new, positionally.
- Writing any constructor removes the free no-argument one.
- Actor subclasses do not normally need super.
If you get stuck
These pages cover the problems that come up most often in this lesson. Opening one is not cheating and it is not counted against you.
Get in Touch
Whether you're a student, parent, or teacher — I'd love to hear from you.
Just want free AP CS resources?
Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]