J. Doe
J. Doe

Reputation: 57

Creating a Constructor with Parameter

this is probably a silly question, but I cant get my program to run.
I have to:

Add a constructor to Hero that only takes a World as a parameter. Do not do anything in the constructor except set the World instance variable to the parameter passed in.

so far I have

public Hero(World world){
    this.world = world;
}

Is this right? Have been trying to call world later on in my program, but it isn't working.

Upvotes: 0

Views: 103

Answers (2)

Deepak Agrawal
Deepak Agrawal

Reputation: 288

It is true that java provides a default no-parameter constructor when you don't define any constructor in your code but when you explicitly define a constructor which takes in some parameters, java doesn't provide the default constructor. Hence, you need to define the default no-parameter constructor here.

public Hero(){

}

Upvotes: 0

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477676

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)

Upvotes: 2

Related Questions