CodeMIRAI
0 XP

Classes and objects

2 min read 6 runnable examples Quiz included

A class is a blueprint, and an object is a thing built from it. String and Scanner are classes other people wrote; now you'll write your own.

Java
class Dog {
    String name;
    int age;

    void bark() {
        System.out.println(name + " says woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog rex = new Dog();
        rex.name = "Rex";
        rex.age = 3;

        Dog bella = new Dog();
        bella.name = "Bella";
        bella.age = 5;

        rex.bark();
        bella.bark();
        System.out.println(rex.name + " is " + rex.age);
    }
}
  • Fields (name, age) hold each object's data, and every object has its own copy.
  • Methods (bark) are what the objects can do. With no static, they work on one particular object, the one before the dot.
  • new Dog() creates an object.
  • A file can contain only one public class, and is named after it. That's why Dog isn't public here.

Methods that read and change fields

Java
class Counter {
    int count;

    void increment() {
        count++;
    }

    void reset() {
        count = 0;
    }

    int get() {
        return count;
    }
}

public class Main {
    public static void main(String[] args) {
        Counter clicks = new Counter();
        Counter visits = new Counter();
        clicks.increment();
        clicks.increment();
        clicks.increment();
        visits.increment();
        System.out.println("clicks " + clicks.get() + ", visits " + visits.get());
        clicks.reset();
        System.out.println("clicks after reset: " + clicks.get());
    }
}

Fields start with default values (0, false or null), which is why count begins at 0.

Variables hold references

Java
class Point {
    int x, y;
}

public class Main {
    public static void main(String[] args) {
        Point a = new Point();
        a.x = 1;
        Point b = a;           // b refers to the same object as a
        b.x = 42;
        System.out.println(a.x);        // 42
        System.out.println(a == b);     // true: the same object

        Point c = new Point();
        c.x = 42;
        System.out.println(a == c);     // false: different objects, even with equal fields
    }
}
VariablesObjects on the heapDog aDog bDog cname = "Rex"age = 3name = "Bella"Dog b = a; copies the reference, not the object: a and b share Rex
An object variable holds a reference. Change Rex through b, and a sees it too; c points somewhere else.

A variable of a class type holds a reference, a pointer to the object, not the object itself. Assigning it copies the reference, not the object.

null

A reference variable that refers to no object holds null. Using it as if it were an object throws a NullPointerException:

Java
class Dog {
    String name = "Rex";
}

public class Main {
    public static void main(String[] args) {
        Dog d = null;
        if (d != null) {
            System.out.println(d.name);
        } else {
            System.out.println("No dog yet");
        }
        System.out.println(d.name);    // NullPointerException
    }
}

The NullPointerException is the most common crash in Java. Check for null wherever a value might be missing.

static and instance members

Java
class Student {
    static int created = 0;    // one variable, shared by the whole class
    String name;               // one per object

    static Student make(String name) {
        Student s = new Student();
        s.name = name;
        created++;
        return s;
    }
}

public class Main {
    public static void main(String[] args) {
        Student a = Student.make("Asha");
        Student b = Student.make("Leo");
        System.out.println(a.name + " and " + b.name);
        System.out.println("Students created: " + Student.created);
    }
}

A static field belongs to the class, so there's a single copy shared by every object, used through the class name: Student.created. A static method belongs to the class too, which is why it can't use an instance field like name without an object.

Printing objects: toString

Java
class Book {
    String title;
    int pages;

    @Override
    public String toString() {
        return title + " (" + pages + " pages)";
    }
}

public class Main {
    public static void main(String[] args) {
        Book b = new Book();
        b.title = "Clean Code";
        b.pages = 464;
        System.out.println(b);    // println calls toString() for you
    }
}

Without that toString method, println would show something like Book@4e25154f. (@Override is explained in the inheritance lesson.)

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.