Skip to content

Child classes and class visibility

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

What flows down, what stays home

// Content.java
public class Content {
    private int rating;
    protected String title;

    public void setRating(int r) {
        rating = r;
    }
}

// Movie.java (same package)
class Movie extends Content {
    void setup(int r, String t) {
        setRating(r);    // โœ… public: inherited
        title = t;       // โœ… protected: inherited
    }
}

Movie uses setRating() and title as if it had written them. Every Movie object still holds a rating too, but only Content's own code can touch it.

Reaching a private field

Naming a parent's private field from the child doesn't compile:

class Movie extends Content {
    void show() {
        System.out.print(rating);         // โŒ rating is private in Content
    }
}

From Movie's point of view, rating doesn't exist. The fix is a door the parent opens on purpose, a getter:

// in Content
public int getRating() {
    return rating;
}

// in Movie
void show() {
    System.out.print(getRating());        // โœ…
}

Remember the rule for members with no modifier: a child inherits them only when both classes share a package.

Which modifiers can a class have?

A top-level class is one not written inside another class. It has only two options:

// StreamingPlatform.java
public class StreamingPlatform { }   // โœ… public: matches the file name
class Catalog { }                    // โœ… package access
class Recommender { }                // โœ… as many as you like
protected class Billing { }          // โŒ doesn't compile
private class Logs { }               // โŒ doesn't compile
Top-level class Allowed?
public โœ… at most one per file, named like the file
no modifier (package access) โœ… any number, any name
protected / private โŒ

Classes declared inside other classes (nested classes) follow other rules, covered later.

Access decides what a child can reach. When a child and its parent, or a parameter and a field, use the same name, this and super decide which one you get.

๐Ÿ’ป Code: Java17_Part_6_Object_Oriented_Basics on GitHub

Next: this and super โ†’