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 Classes

1 Answer

Hi Hariidaran Tamilmaran,

a class in Java is like a Blueprint of an object. A class describes how this object should behave and what for kind of attributes it has.

Let's say I want to create a class for a car. I know it has a name, a color, 3 or 5 doors and so on. These properties don't define the behavior of my car, thus you would add those as variables in the class and not as methods, for expample:

public class Car {
   String color;
   String name;
   int doors;
}

The car can start, you should be able to break and so on. Those properties describe the behavior and would be added as methods to the class:

public class Car {
   String color;
   String name;
   int doors;

   public void startTheCar() {
     // Do something
   }

   public void pressTheBreak() {
     // Do something
   }
}

Now you can take this class (the blueprint) and create a real object of it:

public static void main(String [] args) {
   Car bmw = new car();
   bmw.name = "bmw";
   bmw.color = "black";
   bmw.doors = 5;

   bmw.start()
}

Hope that made it a little bit more clear for you. If you still have questions, please don't hesistate to ask mate.

Jerry Kong
Jerry Kong
5,672 Points

Hi Mario,

Is "object" always a variable? e.g. the number of doors(int), sun roof or not(Boolean), color of paint(String)

Is "method" always a function? e.g. do_something(), do_another_thing()

Edit: I think I'm incorrect. In the example: Car is the class. bmw is the object? name/color are instances variables?

How do we know that those properties "startTheCar()" and "pressThe Break()" relate back to the class "Car"?