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 (Retired) Meet Objects Creating New Objects

Joe Niehaus
Joe Niehaus
2,520 Points

Very Confused!

I am very confused on how to write this code. I simply do not understand it. If someone could help me write this out and explain why we need the different parts that would be awesome, thanks!

Example.java
public class Example {

    public static void main(String[] args) {
        System.out.println("We are going to create a GoKart");
    public}
}

3 Answers

public class Example {

    public static void main(String[] args) {
        System.out.println("We are going to create a GoKart");

      GoKart goKart = new GoKart("Red"); // this line instantiates an object from class GoKart; I gave it the name goKart (it could have been named anything).
      System.out.printf("The color of our new gokart is %s.", goKart.getColor()); //using the new object we created (goKart) I called its method getColor(), 
          //which should return the color that we passed in when we instantiated the object (red).
      //in order to see what is going on you need to understand how the class GoKart was written, 
         //because you are instantiating an object from it so you can use its methods.
    }
}

If you are wondering how the program knows to accept a color when you instantiate the object it is because when you created the class GoKart you created what is called a "constructor" that takes one String parameter (in this case) for your color so any time that you instantiate an object from class GoKart it will always expect a string to be passed in as an argument when you instantiate the object. So in class GoKart your constructor would have looked like this:

public GoKart(String color){  // this is a constructor- it is usually found under your member variable declarations inside your class.
  mColor = color;  // this is where you initialize your member variables from the input given by the user when you instantiate the object.
}
Joe Niehaus
Joe Niehaus
2,520 Points

Thanks, Jeremy! This helps a lot.

Good deal! You're welcome :)