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

need of help

class GoKart { public String color = "red";

public String color() { return color; }

}

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

  public String color() {
    return color;
  }

}

2 Answers

Samuel Moisan
Samuel Moisan
11,953 Points

Hi Dominic,

If you make a method to return the value of the color, you should make your variable private, otherwise your method to get the value of color isn't very useful if you set the variable public.

Look at the example below, Person contains two attributes: firstName and lastName. These are initialized with the constructor whenever an instance of this class is created.

public class Person{
    private String firstName;
    private String lastName;

    public Person(String firstName, String lastName){
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getFirstName(){
        return this.firstName;
    }

    public String getLastName(){
        return this.lastName;
    }
}

After we defined the constructor, we can now create a Person object:

Person me = new Person("John", "Smith");

We can then access the values of firstName and lastName of our newly created Person object using the get methods:

System.out.printf("Hello! My first name is: %s, my last name is: %s.", me.getFirstName(), me.getLastName());

This will print out: Hello! My first name is: John, my last name is: Smith.