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