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 Java Objects Meet Objects Add a Constructor

Java classes

Hey guys! Im completely knew to java, ive done some python and javascript, and boyy are they different. I was introduced to classes a little while ago, and ive managed to solve all tasks to this point. But im stuck here. Could someone tell me what im doing wrong, and if possible give a detailed explanation of exacly why classes are usefull.

In this course hes basicly making us being able to print different names to the console. Hes using classes, and using getters and setters to methods for the class and stuff.. But i dont really get the point of all this, and he does not explain it what so ever.

If all our program does is basicly print different names to the console, why would i not just print it.. I know this sounds like a dumb question to those hwo get it, but i really feel lost here. Ty so much!

GoKart.java
class GoKart {
  private String color = "red";

  public constructor(String color) {
    this.color = color
  }

  public String getColor() {
    return color;
  }
}
Carlos Vallejo
Carlos Vallejo
11,821 Points

Hi

You are creating the constructor wrong, the constructor has to have the same name of the class name, in this case GoKart. The constructor allows you to instantiate when you want to use it.

class GoKart {
private String color = "red";

public GoKart(String color)
{
   this.color = color;
}

public String getColor() 
{
    return color;
}

}

1 Answer

Carlos Vallejo
Carlos Vallejo
11,821 Points

Hi

You are creating the constructor wrong, the constructor has to have the same name of the class name, in this case GoKart. The constructor allows you to instantiate when you want to use it.

class GoKart {
private String color = "red";

public GoKart(String color)
{
   this.color = color;
}

public String getColor() 
{
    return color;
}

}