1 / 73

Inheritance

Inheritance. Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse We will focus on: deriving new classes creating class hierarchies the protected modifier polymorphism via inheritance

paul
Télécharger la présentation

Inheritance

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Inheritance • Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse • We will focus on: • deriving new classes • creating class hierarchies • the protected modifier • polymorphism via inheritance • inheritance used in graphical user interfaces

  2. The Three Pillars of OOP • The Three Pillars of OOP • Encapsulation • Inheritance • Polymorphism • Every class in Java extends some other class. If you don't explicitly specify the class that your new class extends, it will automatically extend the class named Object.

  3. Class Hierarchy • Java uses a class hierarchy to organize its classes. • Thus, all classes in Java exist in a class hierarchy where the class named Object forms the root of the hierarchy. • Some classes extend Object directly, while other classes are subclasses of Object further down the hierarchy.

  4. Inheritance • Inheritance allows a software developer to derive a new class from an existing one • The existing class is called the parent class, or superclass, or base class • The derived class is called the child class or subclass.

  5. Inheritance • As the name implies, the child inherits characteristics of the parent. • That is, the child class inherits the methods and data defined for the parent class • This means that you can write the code for one class and have all its child classes have access to it.

  6. Inheritance Vehicle Car • Inheritance relationships are shown in a UML class diagram using a solid arrow with an unfilled triangular arrowhead pointing to the parent class • Proper inheritance creates an is-a relationship, meaning the child is a more specific version of the parent

  7. Inheritance • A subclass inheritsstate and behavior. • Recall that an object’s state is reflected in the form of instance variables and its behavior in the form of methods. • The child inherits both from all of its ancestors.

  8. Inheritance • Child classes can use the items inherited from its parent or super class as is, or the child class can modify or override the methods of the parent class. • This means that the child class can contain a method with the same name as the parent class.

  9. Inheritance • A programmer can tailor a derived class as needed by adding new variables or methods, or by modifying the inherited ones • Software reuse is a fundamental benefit of inheritance • By using existing software components to create new ones, we capitalize on all the effort that went into the design, implementation, and testing of the existing software

  10. Child Classes • The method in the child class deals with the behavior that is particular to the child class. • We have a class SHAPE and SHAPE has a child class RECTANGLE and a child class TRIANGLE. • The SHAPE class will contain methods that are common to both child classes, e.g. and Area() method • Both child classes will have a method that calculates its Area. • Only the formulas for each Area calculation will differ.

  11. Inheritance • This leads to smaller and easier to understand systems. • Using inheritance, common descriptions can be reused, promoting the concept of code reusability. • A child class can have a method with the same name as the parent class only its method implements what it is capable of doing.

  12. Inheritance • Inheritance cuts redundancy as descendant classes only implement the extra information that differentiates them from the parent class • When changes are made on the common information, all child classes automatically inherit it. • Thus the models that are created are easier to modify and implement. • In Java, the reserved wordextends is used to establish an inheritance relationship

  13. Sub or Child Classes • To declare a subclass you would write: class subclass extends SuperClass { . . . } or, class Dictionary extends Book{…} • A Java class can have only one direct superclass. • Member variables defined in the subclass hide member variables of the same name in the superclass. Consider this superclass and subclass pair:

  14. Sub or Child Classes class Super { protected int num; public Super(int anum){ num = anum; } class Sub extends Super { float num1; public Sub(int newnum, float Fnum) { super(newnum) num1 = Fnum; }

  15. Deriving Subclasses • In Java, we use the reserved word extends to establish an inheritance relationship class Car extends Vehicle { // class contents } • See Words.java • See Book.java • See Dictionary.java

  16. Controlling Inheritance • Visibility modifiers determine which class members get inherited and which do not • Variables and methods declared with public visibility are inherited, and those with private visibility are not • But public variables violate our goal of encapsulation • There is a third visibility modifier that helps in inheritance situations: protected

  17. The protected Modifier • The protected visibility modifier allows a member of a base class to be inherited into the child • The protected visibility modifier provides more encapsulation than public does. • Encapsulation requires that we protect as much as possible out instance variables from outside accesss. • The details of each modifier are given in Appendix F

  18. The protectedModifier • The visibility modifiers determine which class members get inherited and which do not. • Variables and methods declared with public visibility are inherited, and those with private visibility are not. • But public variables violate our goal of encapsulation. • The protectedvisibility modifier allows a member to be inherited, but provides more protection than publicdoes.

  19. The super Reference • Constructors are not inherited, even though they have public visibility • Yet we often want to use the parent's constructor to set up the "parent's part" of the object • The super reference can be used to refer to the parent class, and is often used to invoke the parent's constructor • See Words2.java (page 328) • See Book2.java (page 329) • See Dictionary2.java (page 330)

  20. Class Diagram for Words Book # pages : int + pageMessage() : void Words Dictionary - definitions : int + main (args : String[]) : void + definitionMessage() : void

  21. The Super Reference • The super reference can be used to refer to the parent class, and is often used to invoke the parent's constructor. • In Words2.java, The Dictionary class uses the super reference to call the parent constructor so that the number of pages can be set. • If it did not call the parent constructor, it would have to initialize the number of pages in its own constructor. Let us look at Words2.java

  22. Super Reference • When we create the constructor for a child class, we should invoke the constructor for the superclass also. • To do this, the first line of our constructor should contain the keyword super followed by a parameter list as though calling a method named super(). • The parameter list must match the parameters in the argument list of the superclass constructor.e.g. super(num_pages) // initializes the # of pages

  23. Super Reference • This causes the constructor for the superclass to be invoked using parameters passed from the subclass. • Thus memory is allocated for all the data in the super class. The child class now has full access to it.

  24. Inheritance • The Dictionary class invokes the parent class constructor with: super(num_pages) • Since the Dictionary class inherits the variable pages from the parent class Book, it has to initialize this variable in its constructor. • But the parent class constructor already does this initialization. • Since constructors are not inherited, the Dictionary sub class can use the superreference to invoke the parent class constructor.

  25. The Super Reference • A child object inherits the allowable fields and methods of its parent . The one duty of the default constructor is to support this. • Each instance of a child class inherits the specified methods and variables of the parent class. So the parent class’s instance variables must be properly initialized.

  26. Inheritance and Constructors • Every constructor has 3 tasks to perform: 1. Instantiate the parent object and initialize its fields 2. Initialize any fields local to its class 3. perform the statements in the constructor • If you do not call the parent constructor with super when the super class constructor has parameters, then the instance variables in the parent class will not be initialized.

  27. Defined vs. Inherited • A subtle feature of inheritance is the fact that even if a method or variable is not inherited by a child, it is still defined for that child. • An inherited member can be referenced directly in the child class, as if it were declared in the child class • But even members that are not inherited exist for the child, and can be referenced indirectly through parent methods • In Eating.Java, a pizza object is created that can access private methods and variables in the parent class.

  28. Overriding Methods • A child class canoverride the definition of an inherited method in favor of its own. • This is different from the overloading that we used in Constructors. • That is, a child can redefine a method it inherits from its parent. • The new method must have the same signature as the parent's method, but can have different code in the body

  29. Overriding Methods • See Messages.java • See Thought.java • See Advice.java • Note that a parent method can be explicitly invoked using the super reference

  30. Overloading vs. Overriding • Don't confuse the concepts of overloading and overriding • Overloading deals with multiple methods in the same class with the same name but different signatures • Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature • Overloading lets you define a similar operation in different ways for different data • Overriding lets you define a similar operation in different ways for different object types

  31. Overriding Methods • A subclass can either completely override an inherited method, or the subclass can enhance it. • The subclass can use the keyword super to invoke the version in the superclass. • For instance, if have a method called deposit() in the child class and a method called deposit() in the parent class, the child class would call the parent method with: super.deposit(45.00)

  32. OverRiding • The object type determines which method is invoked. Savings_Account s = new Savings_Account(“Tom”); Account b = new Account(“Bob”); s.deposit(25.00); // defined in Savings_Accountb.deposit(25.00);// method defined in Account class • Don't confuse the concepts of overloading and overriding

  33. Overriding Methods • To overload a method, you must duplicate the method name, but use a different argument list. • To overridea method, you must match the entire method signature. • If you aren't careful when writing your new method signature, you will be overloading methods when you think that you are overriding them. • This is a situation where you don't get any warnings from the JDK compiler.

  34. Overriding • If a method is declared with the final modifier, it cannot be overridden • The concept of overriding can be applied to data and is called shadowing variables • Shadowing variables should be avoided because it tends to cause unnecessarily confusing code

  35. The super Reference Revisited • A method in the parent class can be invoked explicitly using the super reference • The super reference can be used to invoke any method from the parent class. • This ability is often helpful when using overridden methods • The syntax is: super.method(parameters) See Accounts.java

  36. SubClasses • When we extend an existing class, we 'inherit' all of the attributes, and methods, of the parent class. • In the Accounts.java program, the child class can deposit, and withdraw - even though we only explicitly define a new method for withdrawal. • This makes programming much easier, and simpler, as we don't re-invent the wheel each time we extend other classes. • In the example above, we add two new methods , and call the constructor of our parent class.

  37. Class Hierarchies • Two children of the same parent are called siblings. • Good class design puts all common features as high in the hierarchy as is reasonable. • Class hierarchies often have to be extended and modified to keep up with changing needs • There is no single class hierarchy that is appropriate for all situations

  38. Single vs. Multiple Inheritance • Java supports single inheritance, meaning that a derived class can have only one parent class • Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents • Collisions, such as the same variable name in two parents, have to be resolved • In most cases, the use of interfaces gives us the best aspects of multiple inheritance without the overhead

  39. Class Hierarchies Business RetailBusiness ServiceBusiness KMart Macys Penny’s • A child class of one parent can be the parent of another child, forming class hierarchies

  40. The Object Class • A class called Object is defined in the java.lang package of the Java standard class library • All classes are derived from the Object class • If a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class • The Object class is therefore the ultimate root of all class hierarchies

  41. The Object Class • The Object class contains a few useful methods, which are inherited by all classes • For example, the toString method is defined in the Object class • Every time we have defined toString, we have actually been overriding it • The toString method in the Object class is defined to return a string that contains the name of the object’s class and a hash value

  42. Class Object • The class Object defines the following methods: • clone() • equals(Object obj) • finalize() • getClass() • hashCode() • notify() • notifyAll() • toString() • wait() • wait(long timeout) • wait(long timeout, int nanos)  • As you can see, this list includes three overloaded versions of the method named wait (same name, different formal argument lists).

  43. Class Object • Because every class is either a direct or indirect subclass of Object, every class in Java, (including new classes that you define), inherit these eleven methods. • Generally speaking, many of these eleven methods are intended to be overridden for various purposes. • However, some of them, such as getClass, notify, and wait, are intended to be used directly without overriding.

  44. The Object Class • That’s why the println method can call toString for any object that is passed to it – all objects are guaranteed to have a toString method via inheritance • See Academia.java See Student.java • See GradStudent.java • The equals method of the Object class determines if two references are aliases • You may choose to override equals to define equality in some other way

  45. References and Inheritance • Assigning a predecessor object to an ancestor reference is considered to be a widening conversion, and can be performed by simple assignment • Assigning an ancestor object to a predecessor reference can also be done, but it is considered to be a narrowing conversion and must be done with a cast • The widening conversion is the most useful

  46. Polymorphism • What is polymorphism? • The meaning of the word polymorphism is something like one name, many forms. • How does Java implement polymorphism? • Polymorphism manifests itself in Java in the form of multiple methods having the same name.

  47. Polymorphism • In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods). • In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods). Three distinct forms of polymorphism • Method overloading • Method overriding through inheritance • Method overriding through the Java interface

  48. Polymorphism via Inheritance • A polymorphic reference is one which can refer to different types of objects at different times. • Inheritance can also be used as a basis of polymorphism • An object reference can refer to one object at one time, then it can be changed to refer to another object (related by inheritance) at another time

  49. Polymorphism via Inheritance • Suppose the Holiday class has a method called celebrate, and the Christmas class overrode it • Now consider the following invocation: day.celebrate(); • If day refers to a Holiday object, it invokes the Holiday version of celebrate; if it refers to a Christmas object, it invokes the Christmas version

  50. Inheritance Accounts[] customer= new Accounts[10]; Senior_Savings Sam = new Senior_Savings(“Sam”); customer[5] = Sam; Accounts Ricky = new Accounts(“Ricky”); customer[3] = Ricky; So the array customer of class Accounts holds both Senior-Savings and regular Accounts.

More Related