Java 101: Foundations

Java 101: Inheritance in Java, Part 1

Define hierarchical relationships between Java classes

1 2 Page 2
Page 2 of 2

Specifying @Override tells the compiler that the given method overrides another method. If someone attempted to overload the method instead, the compiler would report an error. Without this annotation, the compiler would not report an error because method overloading is legal.

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.)

In conclusion

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 the short Java 101 PDF primer introducing composition, a programming technique wherein you assemble objects from other objects. Composition is a complementary technique to inheritance, which also happens to solve one of its biggest challenges.

1 2 Page 2
Page 2 of 2