Cl

Classes in Java

12 exercises

About Classes

The primary object-oriented construct in Java is the class, which is a combination of data (fields), also known as instance variables, and behavior (methods). The fields and methods of a class are known as its members.

Access to members can be controlled through access modifiers, the two most common ones being:

  • public: the member can be accessed by any code (no restrictions).
  • private: the member can only be accessed by code in the same class.

In Java if no access modifier is specified, the default is package visibility. In this case, the member is visible to all classes defined into the same package.

The above-mentioned grouping of related data and behavior plus restricting access to members is known as encapsulation, which is one of the core object-oriented concepts.

You can think of a class as a template for creating instances of that class. To create an instance of a class (also known as an object), the new keyword is used:

class Car {
}

// Create two car instances
Car myCar = new Car();
Car yourCar = new Car();

Fields have a type and a name (cased in camelCase) and can be defined anywhere in a class (cased in PascalCase).

class Car {
    // Accessible by anyone
    public int weight;

    // Only accessible by code in this class
    private String color;
}

One can optionally assign an initial value to a field. If a field does not specify an initial value, it will be set to its type's default value. An instance's field values can be accessed and updated using dot-notation.

class Car {
    // Will be set to specified value
    public int weight = 2500;

    // Will be set to default value (0)
    public int year;
}

Car newCar = new Car();
newCar.weight; // => 2500
newCar.year;   // => 0

// Update value of the field
newCar.year = 2018;

Private fields are usually updated as a side effect of calling a method. Such methods usually don't return any value, in which case the return type should be void:

class CarImporter {
    private int carsImported;

    public void importCars(int numberOfCars)
    {
        // Update private field
        carsImported = carsImported + numberOfCars;
    }
}

Note that is not customary to use public fields in Java classes. Private fields are typically used which are accessed through getters and setters.

Within a class, the this keyword will refer to the current class. This is especially useful if a parameter has the same name as a field:

class CarImporter {
    private int carsImported;

    public void setImportedCars(int carsImported)
    {
        // Update private field from public method
        this.carsImported = carsImported;
    }
}
Edit via GitHub The link opens in a new window or tab

Learn Classes