This is indeed the way to define a constructor that takes as input a parameter.
A problem you might have overlooked is that when calling the constructor, you have to feed it a value. If you for instance have defined a class Hero
:
public class Hero {
private World world;
public Hero (World world) {
this.world = world;
}
}
You cannot longer construct a Hero
with:
Hero hero = new Hero();
Indeed, the new Hero();
expects a World
. You can for instance first construct a World
and feed it to the hero:
World world = new World();
Hero hero = new Hero(world);
You also have to define a class World
(in a file named World.java
). For instance this stub:
public class World {
}
(If you do not provide a constructor yourself, Java will define a default constructor itself).
Depending on how you compile your project (using an IDE, using the command line,...) you sometimes need to add this file to your project yourself, or compile it with:
javac Hero.java World.java
(and perhaps other .java
files)