0

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.

6
  • What error do you get, please provide a reproducible example together with compiler/runtime output. Commented Mar 1, 2016 at 20:00
  • Are you calling the constructor like: Hero heroVar = new Hero(world)? Commented Mar 1, 2016 at 20:00
  • my compiler is saying it 'Can not find symbol' Commented Mar 1, 2016 at 20:02
  • how is your Hero class defined ? Commented Mar 1, 2016 at 20:03
  • what is the error you are getting? we need to see the msgs!!! Commented Mar 1, 2016 at 20:03

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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(){

}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.