1 / 82

Inheritance

Inheritance. Inheritance is a fundamental object-oriented technique it enhances software design and promotes reuse We will focus on: deriving new classes creating class hierarchies the protected modifier polymorphism via inheritance. The Three Pillars of OOP. Encapsulation

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 • Inheritance is a fundamental object-oriented technique • it enhances software design and promotes reuse • We will focus on: • deriving new classes • creating class hierarchies • the protected modifier • polymorphism via inheritance

  2. The Three Pillars of OOP • Encapsulation • Inheritance • Polymorphism • Every class in Java extends some other class.

  3. Inheritance • If you don't explicitly specify the class that your new class extends • it automatically extend the class Object.

  4. Encapsulation - • By creating class e Student - • and storing in it all the variables and methods • associated with a student we are: • Encapulatingin the Student class • All data pertaining to a student in one place

  5. Class Hierarchy • Java uses a class hierarchy to organize its classes. • All classes in Java exist in a class hierarchy • The Object class forms the root of the hierarchy.

  6. OBJECT CLASS Some classes extend Object directly, while other classes are subclasses of Object further down the hierarchy. The Object class contains methods that are inherited by all its child classes

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

  8. Object class Child class UML OR Unified Modeling Language is used to model an application’s structures, behavior and even business processes PARENT Child PARENT CHILD RELATIONSHIP

  9. Inheritance • The childinherits characteristics of the parent. • The child class inherits the methods and datadefined in the parent class • This means that all child classes have accessto the methods and data.

  10. Vehicle Car • Inheritance relationships are shown in a UML class diagram as solid arrow with an unfilled triangular arrowhead pointing to the parent class • Inheritance creates anis-a relationship, • meaning the child is amore specific version of the parent

  11. Class Car is a subclass of Vehicle and • It inheritsstate and behavior from its parent • An object’s stateis in the form of instance variables • its behavior in the form of methods. • The child inherits both from all of its ancestors.

  12. Class Vehicle extends Object // not necessary • { • // data • // methods ( functions) • } • Class Car extends Vehicle • { • // data - • // methods ( functions) • //some data and methods can be inherited from Vehicle • }

  13. ClassVehicle Method 1 Method 2 Method 3 Class Car Inherits all of the above methods and can add methods of its own

  14. CODE REUSE • A programmer can tailor a child class by : adding new variables or methods, • or by modifying the inherited ones • Software reuse is the fundamental benefit of inheritance

  15. CODE REUSE • We can create new software by reusing • existing software components to create new ones, • we capitalize on all the effort spent on the design,

  16. Class Account deposit() Class SavingsAccount Inherits deposit () Class SeniorAccount Inherits deposit()

  17. Inheritance ///*************MOST IMPORTANT****** • When changes are made on the parent information, • all child classes automatically are changed also. .

  18. CODE REUSE • Thus the models that are created are : • easier to modify and • easier to implement

  19. Concepts to Review • WHAT IS AN “ISA” Relationship? • What is Encapsulation? • What are the benefits of Inheritance? • What does “Code Reuse” mean in terms of efficiency? • What effect does a code change in the parent class have on a child class?

  20. T he reserved wordextends sets up an inheritance relationship • 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.

  21. Sub or Child Classes class ParentClass // the super class { protectedintnum; // instance variable public ParentClass(int num) // constructor { this. num = num; }

  22. class ParentClass { protected intnum; // instance variable public ParentClass (intnum) // constructor { this. num = num; } ******************************************* class ChildClassextendsParentClass { private float num1; // instance variable public ChildClass(intnewnum, float num1) // Constructor { super(newnum); // calls parent class constructor this.num1 = num1; }

  23. Using super • The child class inherits the varible num declared in the parent class ? • How does the child class set up a value for the variable num it inherits?

  24. INHERITANCE • TO create an instance of the Childclass we use: Childclass child = new Childclass ( 20, 30); How does it set up memory for the variable “num ‘ it inherits?

  25. We create a child object : Childclass child = new Childclass ( 20, 30); In the first line of the child’s constructor, public ChildClass(intnewnum, float num1) // child Constructor { // it calls the parent class constructor with this code super(newnum); // calls parent class constructor This is the parent class constructor public ParentClass (intnum) // constructor { this. num = num; } // So the value in newnum is stored in the parent class num

  26. Deriving Subclasses • In Java, we use the reserved word extends to establish an inheritance relationship class Car extends Vehicle { // class contents }

  27. Controlling Inheritance • Visibility modifiers • determine which class members get inherited • Variables and methods declared with public visibility are inherited, and • those with private visibility are not

  28. PROTECTED VISIBILITY MODIFIER • But public instance variables violate our goal of encapsulation • (DO NOT USE THEM IN THIS COURSE!!!) • SO ------- • There is a third visibility modifier : protected

  29. The protected Modifier • The protected visibility modifier allows a • member of a base class to be inherited into the child class • Encapsulation requires that we protect our instance variables from outside access.

  30. Accessibility Summary

  31. Class Book //------------------------------------------------------------------- // Class Book serves as a parent class for class Dictionary //------------------------------------------------------------------- class Book { protected int pages = 1500; //======================================== // Prints a message using the value of an instance variable. //======================================== public void page_message () { System.out.println ("Number of pages: " + pages); } // method page_message } // class Book

  32. //-------------------------------------------------------------------//------------------------------------------------------------------- class Dictionary extends Book { private int definitions = 52500; //========================================= // Prints an instance variable declared in this class and // an instance variable one that it inherited from Book //====================================== public void definition_message () { System.out.println ("# of definitions: " + definitions); System.out.println ("Definitions per page: " + definitions/pages); } // method definition_message } // class Dictionary

  33. Class Words //===================================== // Instantiates a child class and calls its inherited methods. //===================================== public static void main (String[] args) { // create object of Dictionary class(child of Word Class) Dictionary webster = new Dictionary (); webster.page_message(); // method defined in Book class webster.definition_message(); //method in Dictionary class } // method main } OUTPUT: “ Number of pages: 1500” “ # of definitions: 52500/1500 Definitions per page: "

  34. Default Constructor • In the previous slide, we created an object of the Dictionary class. • Dictionary webster = new Dictionary (); • But the Dictionary class has no coded constructor. • How can this be? All classes must have a constructor

  35. default constructor • Answer: • The default constructor is called if a class has no coded constructor. • This happens when instance variables already have a value. • So no constructor is needed.

  36. The Super Reference • Constructors are not inherited, • even though they have public visibility !!!! • So we need to call the parent class constructor • to give values to the instance variables in the parent class • To do this, we use The “super” reference .

  37. The super reference • The super reference in a child constructor calls the parent class constructor. • The call must made in first line of the constructor e.g super(parameters)

  38. //---------------------------------------------------------- // Class Book ‘s constructor initializes pages. // Instance variable “pages” has no value to start //------------------------------------------------------------ class Book 2 { protected int pages; // instance variable //---------------------------------------------------------------- // Sets up a book with the specified number of pages. //---------------------------------------------------------------- public Book 2(intnum_pages) { pages = num_pages; // sets number of pages } // constructor Book } // class Book2

  39. //=======================================// //prints out the number of pages in a book //======================================= public void page_message () { System.out.println ("Number of pages: " + pages); } // method page_message • // Close class Book2

  40. //------------------------------------------------------------------------------------------- // Class Dictionary demonstrates the interaction between the constructors of parent and child classes. // __________________________________________________ class Dictionary2 extends Book 2 { private int definitions; // child class instance variable //----------------------------------------------------------------------------------------- // CONSTRUCTOR USES the super reference to call parent class Book's constructor. //_________________________________________________________ public Dictionary2 (intnum_pages, intnum_definitions) { // “super” calls parent class constructor and sends it the number of pages super (num_pages); definitions = num_definitions; // sets # of definitions } // constructor Dictionary

  41. Dictionary2 class //========================================= // Prints an instance variable declared in this class and // an instance variable one that it inherited from Book //====================================== public void definition_message () { System.out.println ("# of definitions: " + definitions); System.out.println ("Definitions per page: " + definitions/pages); } // method definition_message NOTE that pages is inherited from the parent class

  42. //----------------------------------------------------------// Driver class that creates an object of the Dictionary2 class. //------------------------------------------------------------ class Words2 { public static void main (String[] args) { /// Dictionary2 is child of class Book2 Dictionary2 webster = new Dictionary2 (1500, 52500); //webster calls method from the parent Book class webster.page_message(); // webster calls method from Dictionary class webster.definition_message(); } // method main } // class Words2

  43. Review • I want to create an object of the child class Dictionary2 – • Dictionary2 inherits the number of pages from its parent Book 2 • HOW Did I GIVE A VALUE TO the inherited variable Num_Pages? • How do I create an object of Dictionary2? • How many parameters do I use for the constructor ?

  44. Class Diagram for Words # pages : int + pageMessage() : void Book2 - definitions : int + main (args : String[]) : void + definitionMessage() : void Words2 Dictionary2

  45. The Super Reference – Rules - In Words2.java • The Dictionary2 class uses the super reference to call the parent constructor • so that the number of pages can be set. • Java requires that a child class must call the parent class constructor using “super” IF and ONLY IF the parent class constructor has one or more parameters.

  46. SUPER and Constructors • This insures that the parent class’s instance variables are given values. • If the parent class constructor has no parameters, • the child class is not required to call it. • A default constructor is called for the parent class instead.

  47. Key Terms to Review • Visibility modifiers: protected • The Super Reference

  48. Super Reference - A review • When we create the constructorfor a child class, • we call the constructor for the super class. • This is done in the first line of the sub class constructor • // it initializes the # of pages in parent class variable pages super(num_pages)

  49. OVERLOADED CONSTRUCTORS: We might have a constructor for a Rectangle class with one parameter public Rectangle(int width) { .. Initialize instance variables }

  50. Overloaded Constructors • Another constructor could be defined by a Rectangle with two parameters: public Rectangle(int length, int width) { this.length = length; // shortcut assignment this.width = width } • Both constructors share the same name, • Rectangle(variables) • but they have different parameter lists. 50

More Related