DEV Community

joaofelipefaria
joaofelipefaria

Posted on

[EN] Java in practice: classes, objects and packages

Java is object-oriented

Java is an object-oriented language. In practice, this means we build a Java program by writing classes and manipulating objects. The class is the blueprint; the object is the instance created from it.

Attributes and methods

Inside a class, methods represent an object's behavior and attributes represent its state. To make this concrete, let's model a car, which has a brand and a year of manufacture:

package com.example.model;

public class Car {

    String brand;
    int year;
}
Enter fullscreen mode Exit fullscreen mode

The package

The first statement in a class file is the package declaration. It tells which package the class belongs to and serves three purposes:

  • avoiding naming collisions (two classes with the same name can coexist in different packages);
  • grouping classes by responsibility;
  • allowing other classes to import them.

Creating and using an object

In this example, besides Car, we'll create a second class called Application. It imports Car and, in the main method, creates a car, sets the brand ("fiat uno") and the year (2002), and finally prints both values:

package com.example;

import com.example.model.Car;

public class Application {

    public static void main(String[] args) {
        Car car = new Car();
        car.brand = "fiat uno";
        car.year = 2002;

        System.out.println("Brand: " + car.brand);
        System.out.println("Year: " + car.year);
    }
}
Enter fullscreen mode Exit fullscreen mode

When you run Application, the console prints the brand and year of the car we created. Note that Application lives in a different package from Car, so it needs the import statement to see it.

What we learned

With this small example we've already seen some basic language behaviors: the package declaration, defining a class with its attributes, importing classes, and instantiating an object with new.

About types

By using the keywords String and int, we define the type of each attribute: text for the brand and a whole number for the year. Java is a statically typed language, and this applies to attributes, variables and parameters.

Next steps

In the next articles, we'll dive deeper into typing in Java and explore the possible syntaxes for the main method.

Top comments (0)