Chapter 1-Inheritance PDF
Document Details
![RobustRomanesque](https://quizgecko.com/images/avatars/avatar-11.webp)
Uploaded by RobustRomanesque
Tags
Related
Summary
This document provides an introduction to inheritance in Java. It explains how inheritance promotes code reuse and how it facilitates the creation of more complex classes from simpler, existing ones. The document explores different types of inheritance and their roles in creating software.
Full Transcript
Advance Object Oriented Programming in java Chapter -1- Inheritance 1. Introduction Inheritance A form of software reuse in which a new class is created by absorbing an existing class’s members and reuse them with new or modified capabilities. Can save time duri...
Advance Object Oriented Programming in java Chapter -1- Inheritance 1. Introduction Inheritance A form of software reuse in which a new class is created by absorbing an existing class’s members and reuse them with new or modified capabilities. Can save time during program development by basing new classes on existing proven and debugged high-quality software. Object-Oriented Programming: 2 Inheritance 1. Introduction (Cont.) When creating a class, rather than declaring completely new members, you can designate that the new class should inherit the members of an existing class. Existing class is the superclass New class is the subclass Each subclass can be a superclass of future subclasses. A subclass can add its own fields and methods. A subclass is more specific than its superclass. Object-Oriented Programming: 3 Inheritance 1. Introduction (Cont.) The direct superclass is the superclass from which the subclass explicitly inherits. An indirect superclass is any class above the direct superclass in the class hierarchy. The Java class hierarchy begins with class Object (in package java.lang) Every class in Java directly or indirectly extends (or “inherits from”) Object. Java supports only single inheritance, in which each class is derived from exactly one direct superclass. Is-a represents inheritance In an is-a relationship, an object of a subclass can also be treated as an object of its superclass. Object-Oriented Programming: 4 Inheritance 1. Introduction (Cont.) On the basis of class, there can be three types of inheritance: single, multilevel and hierarchical in java. In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later. Fig. 1 | Types of Inheritance. Object-Oriented Programming: 5 Inheritance 2. Superclasses and Subclasses Figure 2 lists several simple examples of superclasses and subclasses Superclasses tend to be “more general” and subclasses “more specific.” Fig. 2 | Inheritance examples Object-Oriented Programming: 6 Inheritance 2. Superclasses and Subclasses (Cont.) Figure 3 shows a Shape inheritance hierarchy. follow the arrows from the bottom of the diagram to the topmost superclass in this class hierarchy to identify several is-a relationships. A Triangle is a TwoDimensionalShape and is a Shape Cube is a ThreeDimensionalShape and is a Shape. Fig. 3 | Inheritance hierarchy for Shapes. Object-Oriented Programming: 7 Inheritance 3. Super Keyword The super is a reference variable that is used to refer immediate parent class object. Whenever you create the instance of subclass, an instance of parent class is created implicitly. Usage of super Keyword – super is used to refer immediate parent class instance variable. – super is used to invoke immediate parent class method. – super() is used to invoke immediate parent class constructor. Object-Oriented Programming: 8 Inheritance 4. protected Members protected access is an intermediate level of access between public and private. A superclass’s protected members can be accessed by members of that superclass, by members of its subclasses and by members of other classes in the same package protected members also have package access. All public and protected superclass members keep their original access modifier when they become members of the subclass. Object-Oriented Programming: 9 Inheritance 4. protected Members (Cont.) A superclass’s private members are hidden in its subclasses They can be accessed only through the public or protected methods inherited from the superclass Subclass methods can refer to public and protected members inherited from the superclass simply by using the member names. Object-Oriented Programming: 10 Inheritance 5. Method Overriding If subclass (child class) has the same method as declared in the parent class, it is known as method overriding. Rules for Method Overriding method must have same name as in the parent class. method must have same parameter as in the parent class. must be IS-A relationship (inheritance). When a subclass method overrides an inherited superclass method, the superclass method can be accessed from the subclass by preceding the superclass method name with keyword super and a dot (.) separator. Object-Oriented Programming: 11 Inheritance 5.1 Example of Method Overriding In this example, we have defined the run method in the subclass as defined in the parent class. The name and parameter of the method is same. class Vehicle{ void run(){System.out.println("Vehicle is running");} } // the run method of super class class Bike2 extends Vehicle{ void run() {System.out.println("Bike is running safely");} // the run method of sub class public static void main(String args[]){ Bike2 obj = new Bike2(); obj.run(); // calling run method of subclass } Fig. 4 | Example of Method Overriding. Object-Oriented Programming: 12 Inheritance 6. Relationship between Superclasses and Subclasses Inheritance hierarchy containing types of employees in a company’s payroll application Commission employees are paid a percentage of their sales Base-salaried commission employees receive a base salary plus a percentage of their sales. Class CommissionEmployee (Fig.5) extends class Object (from package java.lang). CommissionEmployee inherits Object’s methods. If you don’t explicitly specify which class a new class extends, the class extends Object implicitly. Object-Oriented Programming: 13 Inheritance Fig. 5 | CommissionEmployee class represents an employee paid a percentage of gross sales. (Part 1 of 6.) Object-Oriented Programming: 14 Inheritance Fig. 5 | CommissionEmployee class represents an employee paid a percentage of gross sales. (Part 2 of 6.) Object-Oriented Programming: 15 Inheritance Fig. 5 | CommissionEmployee class represents an employee paid a percentage of gross sales. (Part 3 of 6.) Object-Oriented Programming: 16 Inheritance Fig. 5 | CommissionEmployee class represents an employee paid a percentage of gross sales. (Part 4 of 6.) Object-Oriented Programming: 17 Inheritance Fig. 5 | CommissionEmployee class represents an employee paid a percentage of gross sales. (Part 5 of 6.) Object-Oriented Programming: 18 Inheritance Fig. 5 | CommissionEmployee class represents an employee paid a percentage of gross sales. (Part 6 of 6.) Object-Oriented Programming: 19 Inheritance 6.1 Creating and Using a CommissionEmployee Class (Cont.) Constructors are not inherited. The first task of a subclass constructor is to call its direct superclass’s constructor explicitly or implicitly If the code does not include an explicit call to the superclass constructor, Java implicitly calls the superclass’s default or no-argument constructor. A class’s default constructor calls the superclass’s default or no-argument constructor. Object-Oriented Programming: 20 Inheritance 6.1 Creating and Using a CommissionEmployee Class (Cont.) toString is one of the methods that every class inherits directly or indirectly from class Object. Returns a String representing an object. Class Object’s toString method returns a String that includes the name of the object’s class. Object-Oriented Programming: 21 Inheritance Fig. 6 | CommissioinEmployee class test program. (Part 1 of 2.) Object-Oriented Programming: 22 Inheritance Fig. 6 | CommissioinEmployee class test program. (Part 2 of 2.) Object-Oriented Programming: 23 Inheritance 6.2 Creating and Using a BasePlus- CommissionEmployee Class Class BasePlusCommissionEmployee (Fig. 7) contains a first name, last name, social security number, gross sales amount, commission rate and base salary. All but the base salary are in common with class CommissionEmployee. Class BasePlusCommissionEmployee’s public services include a constructor, and methods earnings, toString and get and set for each instance variable Most of these are in common with class CommissionEmployee. Object-Oriented Programming: 24 Inheritance Fig. 7 | BasePlusCommissionEmployee class represents an employee who receives a base salary in Addition to acommission. (Part 1 of 7.) Object-Oriented Programming: 25 Inheritance Fig. 7 | BasePlusCommissionEmployee class represents an employee who receives a base salary in Addition to acommission. (Part 2 of 7.) Object-Oriented Programming: 26 Inheritance Fig. 7 | BasePlusCommissionEmployee class represents an employee who receives a base salary in Addition to acommission. (Part 3 of 7.) Object-Oriented Programming: 27 Inheritance Fig. 7 | BasePlusCommissionEmployee class represents an employee who receives a base salary in Addition to acommission. (Part 4 of 7.) Object-Oriented Programming: 28 Inheritance Fig. 7 | BasePlusCommissionEmployee class represents an employee who receives a base salary in Addition to acommission. (Part 5 of 7.) Object-Oriented Programming: 29 Inheritance Fig. 7 | BasePlusCommissionEmployee class represents an employee who receives a base salary in Addition to acommission. (Part 6 of 7.) Object-Oriented Programming: 30 Inheritance Fig. 7 | BasePlusCommissionEmployee class represents an employee who receives a base salary in Addition to acommission. (Part 7 of 7.) Object-Oriented Programming: 31 Inheritance 6.2 Creating and Using a BasePlus- CommissionEmployee Class (Cont.) Class BasePlusCommissionEmployee does not specify “extends Object” Implicitly extends Object. BasePlusCommissionEmployee’s constructor invokes class Object’s default constructor implicitly. Object-Oriented Programming: 32 Inheritance Fig. 8 | BasePlusCommissionEmployee test program. (Part 1 of 3.) Object-Oriented Programming: 33 Inheritance Fig. 8 | BasePlusCommissionEmployee test program. (Part 2 of 3.) Object-Oriented Programming: 34 Inheritance Fig. 8 | BasePlusCommissionEmployee test program. (Part 3 of 3.) Object-Oriented Programming: 35 Inheritance 6.2 Creating and Using a BasePlus- CommissionEmployee Class (Cont.) Much of BasePlusCommissionEmployee’s code is similar, or identical, to that of CommissionEmployee. private instance variables firstName and lastName and methods setFirstName, getFirstName, setLastName and getLastName are identical. Both classes also contain corresponding get and set methods. The constructors are almost identical BasePlusCommissionEmployee’s constructor also sets the base-Salary. The toString methods are nearly identical BasePlusCommissionEmployee’s toString also outputs instance variable baseSalary Object-Oriented Programming: 36 Inheritance 6.2 Creating and Using a BasePlus- CommissionEmployee Class (Cont.) We literally copied CommissionEmploye e’s code, pasted it into BasePlusCommissionEmployee, then modified the new class to include a base salary and methods that manipulate the base salary. This “copy-and-paste” approach is often error prone and time consuming. Object-Oriented Programming: 37 Inheritance 6.3 Creating a CommissionEmployee– BasePlusCommissionEmployee Inheritance Hierarchy Class BasePlusCommissionEmployee extends class CommissionEmployee A BasePlusCommissionEmployee object is a CommissionEmployee Inheritance passes on class CommissionEmployee’s capabilities. Class BasePlusCommissionEmployee also has instance variable baseSalary. Subclass BasePlusCommissionEmployee inherits CommissionEmployee’s instance variables and methods Only the superclass’s public and protected members are directly accessible in the subclass. Object-Oriented Programming: 38 Inheritance Fig. 9 | private superclass members cannot be accessed in a subclass. (Part 1 of 5.) Object-Oriented Programming: 39 Inheritance Fig. 9 | private superclass members cannot be accessed in a subclass. (Part 2 of 5.) Object-Oriented Programming: 40 Inheritance Fig. 9 | private superclass members cannot be accessed in a subclass. (Part 3 of 5.) Object-Oriented Programming: 41 Inheritance Fig. 9 | private superclass members cannot be accessed in a subclass. (Part 4 of 5.) Object-Oriented Programming: 42 Inheritance Fig. 9 | private superclass members cannot be accessed in a subclass. (Part 5 of 5.) Object-Oriented Programming: 43 Inheritance 6.3 Creating a CommissionEmployee– BasePlusCommissionEmployee Inheritance Hierarchy (Cont.) Each subclass constructor must implicitly or explicitly call its superclass constructor to initialize the instance variables inherited from the superclass. Superclass constructor call syntax—keyword super, followed by a set of parentheses containing the superclass constructor arguments. Must be the first statement in the subclass constructor’s body. If the subclass constructor did not invoke the superclass’s constructor explicitly, Java would attempt to invoke the superclass’s no-argument or default constructor. Object-Oriented Programming: 44 Inheritance 6.3 Creating a CommissionEmployee– BasePlusCommissionEmployee Inheritance Hierarchy (Cont.) You can explicitly use super() to call the superclass’s no-argument or default constructor, but this is rarely done. Compilation errors occur when the subclass attempts to access the superclass’s private instance variables. These lines could have used appropriate get methods to retrieve the values of the superclass’s instance variables. Object-Oriented Programming: 45 Inheritance 6.4 CommissionEmployee– BasePlusCommissionEmployee Inheritance Hierarchy Using protected Instance Variables To enable a subclass to directly access superclass instance variables, we can declare those members as protected in the superclass. New CommissionEmployee class modified only lines 6–10 of Fig. 5 as follows: protected String firstName; protected String lastName; protected String socialSecurityNumber; protected double grossSales; protected double commissionRate; With protected instance variables, the subclass gets access to the instance variables, but classes that are not subclasses and classes that are not in the same package cannot access these variables directly. Object-Oriented Programming: 46 Inheritance 6.4 CommissionEmployee–BasePlus- CommissionEmployee Inheritance Hierarchy Using protected Instance Variables (Cont.) Class BasePlusCommissionEmployee (Fig. 10) extends the new version of class CommissionEmployee with protected instance variables. These variables are now protected members of BasePlusCommissionEmployee. If another class extends this version of class BasePlusCommissionEmployee, the new subclass also can access the protected members. The source code in Fig. 10 (51 lines) is considerably shorter than that in Fig. 7 (128 lines) Most of the functionality is now inherited from CommissionEmployee There is now only one copy of the functionality. Code is easier to maintain, modify and debug—the code related to a commission employee exists only in class CommissionEmployee. Object-Oriented Programming: 47 Inheritance Fig. 10 | BasePlusCommissionEmployee inherits protected instance variables from CommissionEmployee. (Part 1 of 3.) Object-Oriented Programming: 48 Inheritance Fig. 10 | BasePlusCommissionEmployee inherits protected instance variables from CommissionEmployee. (Part 2 of 3.) Object-Oriented Programming: 49 Inheritance Fig. 10 | BasePlusCommissionEmployee inherits protected instance variables from CommissionEmployee. (Part 3 of 3.) Object-Oriented Programming: 50 Inheritance 6.4 CommissionEmployee–BasePlus- CommissionEmployee Inheritance Hierarchy Using protected Instance Variables (Cont.) Inheriting protected instance variables slightly increases performance, because we can directly access the variables in the subclass without incurring the overhead of a set or get method call. In most cases, it’s better to use private instance variables to encourage proper software engineering, and leave code optimization issues to the compiler. Code will be easier to maintain, modify and debug. Object-Oriented Programming: 51 Inheritance 6.4 CommissionEmployee–BasePlus- CommissionEmployee Inheritance Hierarchy Using protected Instance Variables (Cont.) Using protected instance variables creates several potential problems. The subclass object can set an inherited variable’s value directly without using a set method. A subclass object can assign an invalid value to the variable Subclass methods are more likely to be written so that they depend on the superclass’s data implementation. Subclasses should depend only on the superclass services and not on the superclass data implementation. Object-Oriented Programming: 52 Inheritance 6.4 CommissionEmployee–BasePlus- CommissionEmployee Inheritance Hierarchy Using protected Instance Variables (Cont.) With protected instance variables in the superclass, we may need to modify all the subclasses of the superclass if the superclass implementation changes. Such software is said to be fragile or brittle, because a small change in the superclass can “break” subclass implementation. You should be able to change the superclass implementation while still providing the same services to the subclasses. If the superclass services change, we must reimplement our subclasses. A class’s protected members are visible to all classes in the same package as the class containing the protected members—this is not always desirable. Object-Oriented Programming: 53 Inheritance 6.5 CommissionEmployee–BasePlus- CommissionEmployee Inheritance Hierarchy Using private Instance Variables Hierarchy reengineered using good software engineering practices. Class CommissionEmployee declares instance variables firstName, lastName, socialSecurityNumber, grossSales and commissionRate as private and provides public methods for manipulating these values. Object-Oriented Programming: 54 Inheritance 6.5 CommissionEmployee–BasePlus- CommissionEmployee Inheritance Hierarchy Using private Instance Variables (Cont.) CommissionEmployee methods earnings and toString use the class’s get methods to obtain the values of its instance variables. If we decide to change the internal representation of the data (e.g., variable names) only the bodies of the get and set methods that directly manipulate the instance variables will need to change. These changes occur only within the superclass-—no changes to the subclass are needed. Subclass BasePlusCommissionEmployee inherits Commission-Employee’s non-private methods and can access the private superclass members via those methods. Object-Oriented Programming: 55 Inheritance Fig. 11 | CommissionEmployee class uses methods to manipulate its private Instance variables. (Part 1 of 6.) Object-Oriented Programming: 56 Inheritance Fig. 11 | CommissionEmployee class uses methods to manipulate its private Instance variables. (Part 2 of 6.) Object-Oriented Programming: 57 Inheritance Fig. 11 | CommissionEmployee class uses methods to manipulate its private Instance variables. (Part 3 of 6.) Object-Oriented Programming: 58 Inheritance Fig. 11 | CommissionEmployee class uses methods to manipulate its private Instance variables. (Part 4 of 6.) Object-Oriented Programming: 59 Inheritance Fig. 11 | CommissionEmployee class uses methods to manipulate its private Instance variables. (Part 5 of 6.) Object-Oriented Programming: 60 Inheritance Fig. 11 | CommissionEmployee class uses methods to manipulate its private Instance variables. (Part 6 of 6.) Object-Oriented Programming: 61 Inheritance 6.5 CommissionEmployee–BasePlus- CommissionEmployee Inheritance Hierarchy Using private Instance Variables (Cont.) Class BasePlusCommissionEmployee (Fig. 12) has several changes that distinguish it from Fig. 10. Methods earnings and toString each invoke their superclass versions and do not access instance variables directly. Object-Oriented Programming: 62 Inheritance Fig. 12 | BasePlusCommissionEmployee class inherits from CommissionEmployee and accesses the superclass’s private data via inherited public methods. (Part 1 of 3.) Object-Oriented Programming: 63 Inheritance Fig. 12 | BasePlusCommissionEmployee class inherits from CommissionEmployee and accesses the superclass’s private data via inherited public methods. (Part 2 of 3.) Object-Oriented Programming: 64 Inheritance Fig. 12 | BasePlusCommissionEmployee class inherits from CommissionEmployee and accesses the superclass’s private data via inherited public methods. (Part 3 of 3.) Object-Oriented Programming: 65 Inheritance 6.5 CommissionEmployee–BasePlus- CommissionEmployee Inheritance Hierarchy Using private Instance Variables (Cont.) Method earnings overrides class the superclass’s earnings method. The new version calls CommissionEmployee’s earnings method with super.earnings(). Obtains the earnings based on commission alone Placing the keyword super and a dot (.) separator before the superclass method name invokes the superclass version of an overridden method. Good software engineering practice If a method performs all or some of the actions needed by another method, call that method rather than duplicate its code. Object-Oriented Programming: 66 Inheritance 6.5 CommissionEmployee–BasePlus- CommissionEmployee Inheritance Hierarchy Using private Instance Variables (Cont.) BasePlusCommissionEmployee’s toString method overrides class CommissionEmployee’s toString method. The new version creates part of the String representation by calling CommissionEmployee’s toString method with the expression super.toString(). Object-Oriented Programming: 67 Inheritance 7. Constructors in Subclasses Instantiating a subclass object begins a chain of constructor calls The subclass constructor, before performing its own tasks, invokes its direct superclass’s constructor If the superclass is derived from another class, the superclass constructor invokes the constructor of the next class up the hierarchy, and so on. The last constructor called in the chain is always class Object’s constructor. Original subclass constructor’s body finishes executing last. Object-Oriented Programming: 68 Inheritance 8. Software Engineering with Inheritance When you extend a class, the new class inherits the superclass’s members—though the private superclass members are hidden in the new class. You can customize the new class to meet your needs by including additional members and by overriding superclass members. Doing this does not require the subclass programmer to change the superclass’s source code. Java simply requires access to the superclass’s.class file. Object-Oriented Programming: 69 Inheritance 9. Object Class All classes in Java inherit directly or indirectly from Object, so its 11 methods are inherited by all other classes. Figure 13 summarizes Object’s methods. Fig. 13 | Object Methods. (Part 1 of 3.) Object-Oriented Programming: 70 Inheritance Fig. 13 | Object Methods. (Part 2 of 3.) Object-Oriented Programming: 71 Inheritance Fig. 13 | Object Methods. (Part 3 of 3.) Object-Oriented Programming: 72 Inheritance سوپاس For Listening Object-Oriented Programming: 73 Inheritance