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

Thomas Guarneiri
Thomas Guarneiri
351 Points

What do they mean "new KeyWord"?

The first part of this create an object assignment has me creating a GoKart object, which im pretty sure i did if not then i feel like i am really close. But when i compile it, it comes up with no errors, the problems comes when i check my work it says "please use the new Keyword." I am not entirely sure what this new keyword is. Thank you to anyone who can help me out.

Example.java
public class Example {
    private String goKartColor;
    public static void main(String[] args) {
        System.out.println("We are going to create a GoKart");
    }
  public String GoKart(String color){
   color= goKartColor;
    return goKartColor;
  }
}

2 Answers

Hi Thomas Guarneiri,

with the newkeyword, you create something.

For example:

// 1     2     3     4     5
Animal bear = new Animal("bear");
  • 1 = The data type
  • 2 = the variable name
  • 3 = the new keyword to create an instance of a class
  • 4 = The constructor of the class
  • 5 = a parameter (in this case of the type String)

So, what you only have to do in task one is to create a new GoKart and give it a color as the parameter (of the type String). You can remove the method you wrote since you don't need it.

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hey Thomas,

in Java everething is an object. So you need to create objects/instants of a class somewhere in your code if you need it. With the "new" keyword you instantiate a new object.

MarioΒ΄s example is fine for your understanding.

Animal bear = new Animal("bear");
//here you create a new object/instance of the animal class

Before you create a new object you need to build a parent class (like Animal)

So it should look like this:

public class Animal{
int someIntVariable = 10;
// a variable of the parent class
}

A class is like a blueprint for objects. Inside that class you can declare methods and variables (int someIntVariable) and access them after instantiating (new Animal()) . To acces variables and methods outside the parent class you must use a dot (.) operator.

Animal bear = new Animal("bear");
System.out.println(bear.someIntVariable);

So the output will be 10

I hope this helps a little bit

Grigorij