Java Classes and Objects

Java Classes and Objects

How to create a class in Java

Java is an Oriented Object language and works with classes. A class can represent an object in real life, like a tree or even a car:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
public class Car {

    // property
    private String color;

    // constructor
    public Car(String color) {
        this.color = color;
    }

    // getter
    public String getColor() {
        return color;
    }
}

A class is defined with :

  • properties like color or name
  • constructor which is responsible for creating the object
  • methods like “getColor()” or “runTheCar()”

As we can see, the class has no color defined yet. Let's see how we can create an object and define the color.

How to create an object

  • Create another class named “MyApplication”
  • add a method “main”
  • instantiate your “Car” object
  • print the color of the car
1
2
3
4
5
6
7
public class MyApplication {

    public static void main(String[] args) {
        Car myCar = new Car("red");
        System.out.println("the color of my car is : " + myCar.getColor());
    }
}

It should print in the console this message:

1
the color of my car is : red

Use setters to modify properties

To modify the color, we need to use a “setter” method:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
public class Car {
    private String color;

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

    public String getColor() {
        return color;
    }

    // setter : it will be use to modify the color
    public void setColor(String color) {
        this.color = color;
    }
}

Now we can use this new method in MyApplication class:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class MyApplication {

    public static void main(String[] args) {
        Car myCar = new Car("red");
        System.out.println("the color of my car is : " + myCar.getColor());

        myCar.setColor("blue");
        System.out.println("the new color of my car is : " + myCar.getColor());
    }
}

It should print this result:

1
2
the color of my car is : red
the new color of my car is : blue