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.