Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java

Why doesn't a constructor method have "void"?

Why doesn't a constructor for a class need to have "void", even though it's not returning anything?

public class Forum {
  private String mTopic;

  public Forum(String topic) {
    mTopic = topic;
  }

how come it isn't

public class Forum {
  private String mTopic;

  public void Forum(String topic) {
    mTopic = topic;
  }

Thanks in advance!

2 Answers

This is an explanation I found:

So the reason the constructor doesn't return a value is because it's not called directly by your code, it's called by the memory allocation and object initialization code in the runtime. Its return value (if it actually has one when compiled down to machine code) is opaque to the user - therefore, you can't specify it

Phew, that's quite confusing! So in the end, it still returns something? Just something that we can't specify nor see?

Yeah, so the constructor is code block that is called to initialize a new instance of a class. I have read that it's the "new" operator that calls the constructor that returns the reference of the new object.