Extending a Class

Part of: Inheritance

Why Inheritance? Inheritance lets one class reuse the fields and methods of another. Instead of copying code, you say "this new class is a kind of that existing class." In Java, the keyword extends creates this relationship. The class being extended is the superclass (also called the parent or base class). The class doing the extending is the subclass (child or derived class). A subclass automatically receives all public and protected members of its superclass. The extends Keyword Here Dog inherits breathe() from Animal. A Dog object can call both bark() and breathe(), even though breathe() is written only once, in Animal. Key Rules - A class can extend only one superclass (Java has single inheritance). - The subclass adds new behavior while keeping inherited behavior. - private members exist in the subclass but cannot be accessed directly by name. - If you do not write extends, your class implicitly extends Object. Reusing Code The big win is code reuse . If ten kinds of animals all breathe the same way, you write breathe() once in Animal. Every subclass gets it for free, and a fix in one place fixes all of them. Think of inheritance as building a family tree of types. The closer

Challenge: Inherited Greeting