6.8. Summary

We started the chapter with a discussion of inheritance and polymorphism, using an example from everyday life: all creatures inherit the properties and behavior of their parents, and the same action (such as reproduce) may have different meanings for different species. Inheritance enables the reuse of existing code, and it can be implemented using classes and interfaces. A class can’t extend more than one class, but it can implement more than one interface. Inheriting a class is also called subclassing, and the inherited class is referred to as the base or parent class. A class that inherits another class or implements an interface is called a derived class or subclass.

Just as it’s common to address someone using a last name or family name, an object of a derived class can be referred to with a variable of a base class or an interface that it implements. But when you refer to an object using a variable of the base class, the variable can access only the members defined in the base class. Similarly, a variable of type interface can access only the members defined in that interface. Even with this limitation, you may wish to refer to objects using variables of their base class to work with multiple objects that have common base classes.

Objects of related classes—the ones that share an inheritance relationship—can be cast to another object. You may wish to cast an object when you wish to access its members that aren’t available by default using the variable that’s used to refer to the object.

The keywords this and super are object references and are used to access an object and its base class, respectively. You can use the keyword this to access a class’s variables, methods, and constructors. Similarly, the keyword super is used to access a base class’s variables, methods, and constructors.

Polymorphism is the ability of objects to execute methods defined in a superclass or base class, depending on their type. Classes that share an inheritance relationship exhibit polymorphism. The polymorphic method should be defined in both the base class and the inherited class.

You can implement polymorphism by using either classes or interfaces. In the case of polymorphism with classes, the base class can be either an abstract class or a concrete class. The method in question here also need not be an abstract method. When you implement polymorphism using interfaces, you must use an abstract method from the interface.

Java 8 enables you to write code declaratively. We covered lambda expressions, their syntax, and the interface Predicate.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.135.225