Introduction to the Lesson

Welcome back! In this lesson, we're going to explore a critical area of inheritance in Java: overriding methods and attributes. It's akin to taking a classic recipe, the parent class, and tweaking it to suit your unique taste, the child class. Let's begin!

Recap of Inheritance

Inheritance in Java allows a class, referred to as a child, to 'inherit' properties and behaviors from another class, the parent. This is achieved using the keyword extends.

In this example, Smartphone inherits all aspects of CellPhone.

Overriding Methods in Inheritance

Overriding enables a child class to customize inherited methods. When a child class declares a method that is already present in the parent class, we refer to this as method overriding.

Here's an example of how Smartphone overrides a method in CellPhone:

In this case, Smartphone overrides the displayBatteryStatus method to implement a unique action.

Overriding Attributes in Inheritance

Child classes can also override inherited attributes. For instance, CellPhone possesses an attribute named hasTouchScreen, which is set to false. In contrast, Smartphone changes this attribute as it does feature a touchscreen.

Here, Smartphone overrides the hasTouchScreen attribute to reflect its unique capabilities accurately.

Understanding 'protected' in Java

The protected identifier in Java serves as a mid-point between private and public. When marked protected, an attribute becomes accessible within all subclasses.

In this scenario, Smartphone is allowed to access and override the protected attribute hasPhysicalKeypad. At the same time, just directly accessing the same field, or accessing it from a non-inherited class, doesn't work.

Lesson Summary and Practice

Great progress today! You have explored the concepts of method and attribute overriding and discovered the use of protected in Java. Brace yourself for the upcoming exercises, where you will apply these concepts using the CellPhone and Smartphone classes. Let's get started!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal