Java Language Basics

Inheritance in Java, Part 1: The extends keyword

Use Java's extends keyword to derive a child class from a parent class, invoke parent class constructors and methods, override methods, and more

1 2 Page 2
Page 2 of 2

Method overriding and protected methods

Java provides the protected keyword for use in a method-overriding context. You can also use protected for fields. This keyword is commonly used to identify methods that are designed to be overridden, given that not all accessible methods should be overridden.

When you declare a method or field protected, the method or field is accessible to all of the code within any class that has been declared in the same package. It's also accessible to subclasses regardless of their packages. (I'll discuss packages in a future article.)

Conclusion: Inheritance vs composition

The second half of this introduction to inheritance tours the Object class and its methods. Every Java class inherits from Object, so familiarity with this superclass is fundamental to understanding the Java class hierarchy. Also see my Java tip introducing composition vs inheritance. Composition offers an important alternative to inheritance for creating relationships between classes. It also happens to solve one of the biggest challenges with inheritance.

1 2 Page 2
Page 2 of 2