Skip to content

Anatomy of a class: fields and methods

โ˜• Java 17 ยท Your First Java Class ยท 1/3

A class is a blueprint

An architect's plan isn't a house, but it describes everything about the house. A class works the same way: it describes what an object looks like and what it can do.

public class Movie {

    String title;
    int releaseYear;

    public String getTitle() {
        return title;
    }
}
Part In the example Role
class + name class Movie declares the blueprint; class names start with an uppercase letter
Fields title, releaseYear the object's data (its state)
Methods getTitle() the object's behavior: what it can do

Fields: the data

A field is a variable that lives inside a class. It answers the question what do we need to know about a movie? Every field has a type and a name:

public class Movie {
    String title;          // text
    String genre;
    int releaseYear;       // whole number
    double rating;         // decimal number
    boolean isAvailable;   // true or false
}
Type Holds Example value
String text "Inception", "Action"
int whole numbers 2010
double decimal numbers 8.5
boolean true or false is the movie available to stream?

These four types cover most of the data you'll store at first. More types come later in the course.

Methods: the behavior

A method is something the object can do. It has a return type, a name, optional parameters and a body:

public class Movie {
    String title;

    public String getTitle() {               // returns a String
        return title;
    }

    public int countWatchers(int month) {    // takes an int parameter
        return 10;
    }

    public void markUnavailable() {          // returns nothing
        // no value returned
    }
}
Part Example Meaning
Return type String, int, void what the method gives back; void means nothing
Name getTitle, markUnavailable a verb describing the action
Parameters (int month) input values; empty () means none
Body { ... } the code that runs when the method is called

public means the method can be called from anywhere. Access modifiers get their own section later.

A class with fields and methods is a good start, but it can't run on its own yet. Next: comments, how classes map to files, and the main method.

๐Ÿ’ป Code: Java17_Part_1_Fundamentals_Core_Syntax on GitHub

Next: comments, files and the main method โ†’