Java Building Blocks: Java Classes Updated 2023

·

3 min read

Classes are the most basic building blocks in Java. A class is like a blueprint of an object that you want to use over and over again. Below is the simplest form of a Java class.

public class Car {}

This is just a class, and it does nothing.

A class has two primary elements: methods and fields. A method is simply a function inside a Java class. A field is just a variable, interchangeably, you can use any of the other, but for Java's sake, we will call these how they are called expectedly in the Java exam.

Sample of a method:

public String getColor() { return color }

In the above sample method, the method name is getColor. Inside the getColor method is a field being returned named color. We want to make sense of the above snippet so we'll fit this inside the Car class.

public class Car {
    String color;
    public String color() {
        return color;
    }
}

Now this is a class that has a method(getColor) and a field(color) in it.

Let's leave this concept here and we'll get back here after we tackle the Java main method.


Java main() Method

The java main method is the main entrypoint of any Java app. When we run a java file, the method that it bootstraps is the main method and it commonly looks like the one below:

public static void main(String[] args) {}

Piecing it together...

We have this Car class.

public class Car {
    String color;
    public String getColor() {
        return color;
    }
}

And we have the main method

public static void main(String[] args) {}

Challenge: We want to give a value to the color field of the Car class and print it inside the main method. (You can refrain from checking the next code box as I will provide an answer in it But feel free to do so if you wanna checkout right away how this one will look like, no pressure.)

public class Car {
    String color;
    public String getColor() {
        return color;
    }
}
public static void main(String[] args) {
    Car myCar = new Car();
    myCar.color = "pink";
    System,out.println("My car color: " + myCar.getColor);
}

Save this as Car.java


Let me skip the formalities on how to run a java program with a "Hello World" string. It's nice to deviate from the mainstream at times. Just follow the steps below to run your java program.

  1. Open a command line and browse to the directory where you saved Car.java.

  2. Type: javac Car.java then hit enter to compile your code.

  3. Now, type ' java Car ' to run your program.

If you are encountering an error when trying to run any steps in the above instructions, more specifically this error: "not recognized as an internal or external command"*, you can read my other article on [how to install Java](misscharm.hashnode.dev/java-install-jdk-17-..) on your machine.*

The output of the program should print the following:

My car color: pink