Skip to content

this and super

โ˜• Java 17 ยท Building Child Classes with this and super ยท 2/3

Two names can collide: a parameter and a field, or a child's field and its parent's. Two keywords resolve it.

A parameter can hide a field

public class Series {
    private String name;

    void setName(String name) {
        name = name;        // โš ๏ธ compiles, but the field stays null
    }
}

Inside the method, Java always picks the closest name: the parameter. name = name copies the parameter into itself, and the field never changes. No error, no warning: a silent bug.

this means the current object, so this.name skips the parameter and reaches the field:

void setName(String name) {
    this.name = name;   // โœ… field = parameter
}

The rules of this

public class Episode {
    private int number;
    private int duration;
    private String status;

    void set(int number, int mins) {
        number = this.number;    // โš ๏ธ backwards: copies the field INTO the parameter
        duration = mins;         // โœ… no name clash: this isn't needed
        this.status = "ready";   // โœ… allowed, even without a clash
    }

    static void reset() {
        this.status = null;      // โŒ no object in static code
    }
}
  • Watch the direction: the value on the right goes into the variable on the left.
  • Without a name clash, this is optional.
  • this needs an object, so it never compiles in static code.

super reaches the parent's version

A child can declare a field with the same name as an inherited one. The object then holds two fields:

public class Content {
    protected int quality = 1080;
}

public class Movie extends Content {
    protected int quality = 2160;

    int mine()   { return quality; }         // 2160: Movie's own field
    int parent() { return super.quality; }   // 1080: the inherited one
}

The child's field hides the parent's. super.quality skips the current class and reads only what was inherited.

How Java finds a name

Written as Where Java looks
quality local variables and parameters first, then the current class, then the parents
this.quality the current class, then the parents
super.quality the parents only, never the current class

So super.x doesn't compile if x exists only in the child, while this.x sees both. Neither works in static code.

The lab puts both keywords to work on a premium subscription.

๐Ÿ’ป Code: Java17_Part_6_Object_Oriented_Basics on GitHub

โ† Child classes and visibility ยท Next: the lab โ†’