Skip to content

Family rules: final, one parent, Object

โ˜• Java 17 ยท Building Classes on Top of Other Classes ยท 2/3

You can now build a child class and know what it inherits. Three rules shape every hierarchy.

final: no children

A final class can never be extended:

public class Subscription { }

public final class PremiumPlan extends Subscription { }   // โœ… final, with a parent

public class FamilyPlan extends PremiumPlan { }           // โŒ PremiumPlan is final

final stops a class from having children, not from having a parent. PremiumPlan extends Subscription just fine; it simply ends its branch of the tree.

Other class modifiers (abstract, sealed, non-sealed) come in later sections.

One direct parent

Every class has exactly one direct parent:

class Movie extends Content { }         // โœ… one parent
class Documentary extends Movie { }     // โœ… several levels
class Trailer extends Movie, Clip { }   // โŒ two parents

This is single inheritance: one class name after extends, never two. A parent can have many children (Movie and Series both extend Content), and the tree can be as deep as you need.

A class can, however, implement several interfaces: that's how Java offers multiple types without multiple parents. Interfaces come in a later chapter.

Object: the ancestor of every class

A class without extends still has a parent:

// what you write
public class User { }

// what the compiler sees
public class User extends java.lang.Object { }

The compiler adds extends java.lang.Object automatically. That's why this works, even though User declares no method:

User user = new User();
String text = user.toString();   // inherited from Object

Object is the only class with no parent: every hierarchy ends there. Primitives like int and boolean aren't classes, so they're outside this tree; their wrappers (Integer, Boolean) are inside it.

A full hierarchy for our platform looks like this:

Object
 โ””โ”€ Content
     โ”œโ”€ Movie
     โ”‚   โ””โ”€ Documentary
     โ””โ”€ Series

The lab builds exactly this tree.

๐Ÿ’ป Code: Java17_Part_6_Object_Oriented_Basics on GitHub

โ† extends and inheritance ยท Next: the lab โ†’