820 likes | 961 Views
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
E N D
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 • Inheritance • Polymorphism • Every class in Java extends some other class.
Inheritance • If you don't explicitly specify the class that your new class extends • it automatically extend the class Object.
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
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.
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
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.
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
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.
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
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.
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 • }
ClassVehicle Method 1 Method 2 Method 3 Class Car Inherits all of the above methods and can add methods of its own
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
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,
Class Account deposit() Class SavingsAccount Inherits deposit () Class SeniorAccount Inherits deposit()
Inheritance ///*************MOST IMPORTANT****** • When changes are made on the parent information, • all child classes automatically are changed also. .
CODE REUSE • Thus the models that are created are : • easier to modify and • easier to implement
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?
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.
Sub or Child Classes class ParentClass // the super class { protectedintnum; // instance variable public ParentClass(int num) // constructor { this. num = num; }
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; }
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?
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?
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
Deriving Subclasses • In Java, we use the reserved word extends to establish an inheritance relationship class Car extends Vehicle { // class contents }
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
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
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.
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
//-------------------------------------------------------------------//------------------------------------------------------------------- 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
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: "
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
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.
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 .
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)
//---------------------------------------------------------- // 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
//=======================================// //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
//------------------------------------------------------------------------------------------- // 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
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
//----------------------------------------------------------// 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
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 ?
Class Diagram for Words # pages : int + pageMessage() : void Book2 - definitions : int + main (args : String[]) : void + definitionMessage() : void Words2 Dictionary2
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.
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.
Key Terms to Review • Visibility modifiers: protected • The Super Reference
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)
OVERLOADED CONSTRUCTORS: We might have a constructor for a Rectangle class with one parameter public Rectangle(int width) { .. Initialize instance variables }
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