Presentation is loading. Please wait.

Presentation is loading. Please wait.

1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:

Similar presentations


Presentation on theme: "1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:"— Presentation transcript:

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

2 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 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 4Inheritance  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 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 6 ClassVehicle Method 1 Method 2 Method 3 Class Car Inherits all of the above methods

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

8 8Inheritance  A subclass inherits state 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.

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

10 10Inheritance  A programmer can tailor a child 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

11 11 Child Classes  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. But will over ride the parent method.  Only the formulas for each Area calculation will differ.  The method in the child class deals with the behavior that is particular to the child class.

12 12 Class Shape Area () Class Triangle Inherits Area() Class Rectangle Inherits Area()

13 13 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.

14 14Inheritance  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.

15 15 Sub or Child Classes  In Java, the reserved word extends is used to establish an inheritance relationship  To declare a subclass you would write: class subclass extends SuperClass {... } or, class subclass extends SuperClass {... } or, class Dictionary extends Book{…} class Dictionary extends Book{…}  A Java class can have only one direct superclass.

16 16 Sub or Child Classes class Super { protected int num; // instance variable protected int num; // instance variable public Super(int num) // constructor public Super(int num) // constructor { this. num = num; this. num = num;} class Sub extends Super { private float num1; // instance variable public Sub(int newnum, float num1) public Sub(int newnum, float num1) { super(newnum); // calls parent class constructor super(newnum); // calls parent class constructor this.num1 = num1; this.num1 = num1;}

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

18 18 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

19 19 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

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

21 21 //------------------------------------------------------------------- class Dictionary extends Book { private int definitions = 52500; 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 () public void definition_message () { System.out.println ("# of definitions: " + definitions); System.out.println ("# of definitions: " + definitions); System.out.println ("Definitions per page: " + System.out.println ("Definitions per page: " + definitions/pages); definitions/pages); } // method definition_message } // method definition_message } // class Dictionary

22 22 Class Words class Words {//===================================== // Instantiates a child class and invokes its inherited methods. //===================================== public static void main (String[] args) public static void main (String[] args){ Dictionary webster = new Dictionary (); Dictionary webster = new Dictionary (); webster.page_message(); webster.page_message(); webster.definition_message(); webster.definition_message(); } // method main } // method main } // class Words

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

24 24 //---------------------------------------------------------- // Class Book ‘s constructor initializes pages //------------------------------------------------------------ class Book { protected int pages; // instance variable protected int pages; // instance variable //======================================= //======================================= // Sets up a book with the specified number of pages. // Sets up a book with the specified number of pages. //====================================== //====================================== public Book (int num_pages) public Book (int num_pages) { pages = num_pages; // sets number of pages pages = num_pages; // sets number of pages } // constructor Book } // constructor Book //=======================================// //prints out the number of pages in a book //======================================= public void page_message () public void page_message () { System.out.println ("Number of pages: " + pages); System.out.println ("Number of pages: " + pages); } // method page_message } // method page_message } // class Book

25 25 //======================================= // Class Dictionary demonstrates the interaction between the constructors of parent and child classes. //======================================= class Dictionary extends Book { private int definitions; private int definitions; //====================================== //====================================== // Uses the super reference to call Book's constructor. //========================================= public Dictionary (int num_pages, int num_definitions) public Dictionary (int num_pages, int num_definitions){ // sets the # of pages in parent class // sets the # of pages in parent class super (num_pages); super (num_pages); definitions = num_definitions; // sets # of definitions definitions = num_definitions; // sets # of definitions } // constructor Dictionary } // constructor Dictionary

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

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

28 28 The Super Reference - Rules  In Words2.java, The Dictionary 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 the parent class constructor has a parameter.  This is to insure 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.

29 29 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.  The parameter list must match the parameters in the argument list of the superclass constructor.e.g.  super(num_pages) // initializes the # of pages super(num_pages) // initializes the # of pages

30 30 Super Reference  This causes the constructor for the superclass to be invoked using parameters passed from the subclass.  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.

31 31 Inheritance and Constructors  Every constructor has 3 tasks to perform: 1. Instantiate the parent object and initialize its 1. Instantiate the parent object and initialize its fields fields 2. Initialize any fields local to its class 2. Initialize any fields local to its class 3. perform the statements in the constructor 3. perform the statements in the constructor

32 32 Overloaded Constructors  Another constructor that could be defined by Rectangle: public Rectangle(int Newlength, int Newwidth) { length = Newlength; width = Newwidth }  Both constructors share the same name, Rectangle, but they have different parameter lists.  The compiler determines which constructors to use based on the number and types of the parameters/

33 33 Overloading Methods  Method overloading is the process of using the same method name for multiple methods. The signature of each overloaded method must be unique  The signature is based on the number, type, and order of the parameters.  The compiler must be able to determine which version of the method is being invoked by analyzing the parameters. Thus, one method must differ from another by the number and type of parameters it uses.  The return type of the method is not part of the signature

34 34 Overloading Methods int tryMe (int x) { return x*x; } Version 1 int tryMe (int x, float y) { return x*y; } Version 2 result = tryMe (25, 4.32)Invocation

35 35 Overloaded Methods  The println method is overloaded: println (String s) println (int i) println (double d) etc.  The following lines invoke different versions of the println method: System.out.println ("The total is:"); System.out.println (total);

36 36 Overriding Methods  A child class can override 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

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

38 38 //********************************************** // Contains a method that is overridden in a child class. //********************************************** class Thought { public void message() public void message() { System.out.println ("I feel like I'm diagonally parked " + "in a parallel universe."); System.out.println ("I feel like I'm diagonally parked " + "in a parallel universe."); } // method message } // method message } // class Thought

39 39 //********************************************** // Class Advice overrides the message method. //********************************************** class Advice extends Thought { // This method overrides the parent version public void message() public void message() { System.out.println ("Warning: Dates in calendar are " + "closer than they appear."); System.out.println ("Warning: Dates in calendar are " + "closer than they appear."); } // method message } // class Advice

40 40 ///********************************************** // Driver class that creates objects of parent and child //classes. //********************************************** class Messages { public static void main (String[] args) { Thought parked = new Thought (); // create Thought object Thought parked = new Thought (); // create Thought object Advice dates = new Advice();// create Advice object Advice dates = new Advice();// create Advice object parked.message(); // calls method in Thought class parked.message(); // calls method in Thought class dates.message(); // calls method in Advice class dates.message(); // calls method in Advice class } // method main } // method main } // class Messages

41 41 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

42 42 Overriding Methods  To overload a method, you must duplicate the method name, but use a different argument list.  To override a method, you must match the entire method signature.

43 43Overriding  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. This occurs when you use the same variable names in both the child and parent classes  Shadowing variables should be avoided because it tends to cause unnecessarily confusing code

44 44 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

45 45 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

46 46 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

47 47 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

48 48 Class Object  The class Object defines the following methods: clone()clone() equals(Object obj)equals(Object obj) finalize()finalize() getClass()getClass() hashCode()hashCode() notify()notify() notifyAll()notifyAll() toString()toString() wait()wait() wait(long timeout)wait(long timeout) wait(long timeout, int nanos)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).

49 49 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.

50 50 The super Reference Revisited  A method in the parent class can be invoked explicitly using the super reference  This ability is often helpful when using overridden methods  The syntax is: super.method(parameters) super.method(parameters)  For instance, in the next example, the toString method in a child class calls the toString method in the parent class with:  super.toString();

51 51 public class Student { protected String Firstname, Lastname; protected String Firstname, Lastname; protected int numCourses; protected int numCourses; //----------------------------------------------------------------- //----------------------------------------------------------------- // Sets up a student with a name and number of courses. // Sets up a student with a name and number of courses. //----------------------------------------------------------------- //----------------------------------------------------------------- public Student (String Firstname, String Lastname, int numCourses) public Student (String Firstname, String Lastname, int numCourses) { this.Firstname = Firstname; this.Firstname = Firstname; this. Lastname = LastName this.numCourses = numCourses; this.numCourses = numCourses; } //----------------------------------------------------------------- //----------------------------------------------------------------- // Returns information about this student as a string. // Returns information about this student as a string. //----------------------------------------------------------------- //----------------------------------------------------------------- public String toString () public String toString () { String result = "Student name: " + Firstname + “ “ + Lastname "\n"; String result = "Student name: " + Firstname + “ “ + Lastname "\n"; result += "Number of courses: " + numCourses; result += "Number of courses: " + numCourses; return result; return result; }

52 52 //method to compare two objects public boolean equals(Object other) { boolean result; boolean result; if (LastName.equals(((Student)other).LastName)) if (LastName.equals(((Student)other).LastName)) result = FirstName.equals(((Student)other).FirstName); result = FirstName.equals(((Student)other).FirstName); else else result = LastName.equals(((Student)other).LastName); result = LastName.equals(((Student)other).LastName); return result; return result; }}

53 53 public class GradStudent extends Student { private String source; private String source; private double rate; private double rate; //---------------------------------------------------------- //---------------------------------------------------------- // Sets up the gradate student using the specified // information. //------------------------------------------------------------- public GradStudent (String Fastname, String LastName,int numCourses, String source, double rate) { public GradStudent (String Fastname, String LastName,int numCourses, String source, double rate) { super (Firstname, Lastname, numCourses); super (Firstname, Lastname, numCourses); this.source = source; this.source = source; this.rate = rate; this.rate = rate; } //----------------------------------------------------------------- //----------------------------------------------------------------- // Returns a description of this graduate student as a string. – uses super to call parent class toString() //----------------------------------------------------------------- public String toString (){ public String toString (){ String result = super.toString(); String result = super.toString(); result += "\nSupport source: " + source + "\n“ + "Hourly pay rate: " + rate; result += "\nSupport source: " + source + "\n“ + "Hourly pay rate: " + rate; return result; return result; }} }}

54 54 class Academia { //---------------------------------------------------- //---------------------------------------------------- // Creates objects of two student types, prints some //information about them, then checks them for //equality. // Creates objects of two student types, prints some //information about them, then checks them for //equality. //----------------------------------------------------- //----------------------------------------------------- public static void main (String[] args) public static void main (String[] args){ Student susan = new Student ("Susan", “James”, 4); Student susan = new Student ("Susan", “James”, 4); GradStudent Paul = new GradStudent ("Paul",”McCartney”, 1); GradStudent Paul = new GradStudent ("Paul",”McCartney”, 1); System.out.println (susan); System.out.println (susan); System.out.println (); System.out.println (); System.out.println (Paul); System.out.println (Paul); System.out.println (); System.out.println (); if (! susan.equals(Paul)) if (! susan.equals(Paul)) System.out.println ("These are two different students."); System.out.println ("These are two different students."); }}

55 55 References and Inheritance  An object reference can refer to an object of its class, or to an object of any class related to it by inheritance  For example, if the Holiday class is used to derive a child class called Christmas, then a Holiday reference could actually be used to point to a Christmas object  I can do:  Holiday day = new Holiday();  Christmas day = new Christmas(); Holiday Christmas OR: Holiday day; day = new Christmas();

56 56 References and Inheritance  Assigning a child object to an ancestor reference is considered to be a widening conversion, and can be performed by simple assignment  Assigning an ancestor(parent) object to child 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

57 57 Widening VS Narrowing Conversion  The only direct legal way to do a conversion is a widening conversion.  A child object may be stored in an parent object as this is a widening conversion  A parent object may not be stored in a child as it is a narrowing conversion;  Legal parent = child  Error child = parent

58 58 Conversion  Legal student = gradstudent(child)  Error gradstudent = student(parent)  It is possible to store a child in a parent under certain circumstances which we will address in the homework.

59 59Polymorphism  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.

60 60Polymorphism  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

61 61 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

62 62 Class Account # balance: double + deposit() : double Class Senior Savings Inherits other parent methods and variables + withdraw() : double + deposit() : double Over rides parent version

63 63  We have an Accounts class which contains a deposit and withdraw method. The SeniorSavings class extends it.  We create an array of Accounts objects. Accounts[] customer= new Accounts[10];  We create an object of the Senior_Savings class Senior_Savings Sam = new Senior_Savings(“Sam”);  We store Sam in the array customer[5] = Sam; customer[5] = Sam;  We create an Accounts object called Ricky and store it in the array Accounts Ricky = new Accounts(“Ricky”); customer[3] = Ricky;  So the array customer of class Accounts holds both Senior-Savings and regular Accounts because the two classes are related by inheritance

64 64 Polymorphism  The Senior_Savings class extends the Account class and overrides the Account class method deposit with a deposit method of its own.  The deposit method that is called depends on what type of object is in the array.  If the object is a SeniorSavings object, its deposit method will be called. If it is an Account object, the parent version is called.

65 65 public class Bank { public static void main(String args[]) { Account [] customer = new Account[10]; Account [] customer = new Account[10]; for (int i=0; i< 3; i++) for (int i=0; i< 3; i++){ System.out.print ("Name of customer:); System.out.print ("Name of customer:); String name = scan.next(); String name = scan.next(); System.out.print ("Type of Account: S for Senior, R for regular "); System.out.print ("Type of Account: S for Senior, R for regular "); String type = scan.next(); String type = scan.next(); if(type.charAt(0) == 'S') if(type.charAt(0) == 'S') customer[i] = new Senior_Savings(Name, acctype,accountnumber); customer[i] = new Senior_Savings(Name, acctype,accountnumber); else if (acctype == 'R’) else if (acctype == 'R’) customer[i] = new Account(Name, acctype, accountnumber); customer[i] = new Account(Name, acctype, accountnumber); } // close for } // close for

66 66  When we call the deposit method in a loop, the deposit method that is is called depends on whether the object in the array is of the Account class or the SeniorSavings class. if(acctype == 'S') if(acctype == 'S') { customer[i] = new SeniorSavings( name, acctype, accnum++); customer[i].deposit(45); // SeniorSavings version called } else if (acctype == 'R’) customer[i].deposit(45); // SeniorSavings version called } else if (acctype == 'R’) { customer [i] = new Account(name, acctype, acctnum++); customer [i] = new Account(name, acctype, acctnum++); customer[i].deposit(75); // Account version called } customer[i].deposit(75); // Account version called }

67 Another Polymorphism Example Let’s look at another example of polymorphism. Recall the classes we did earlier, classes Advice and Thought. Class Advice extends class Thought and overrides the message method; 67

68 68 Class Thought // Class Thought has one method /*************************************************** class Thought { public void message() public void message(){ System.out.println ("Some people get lost in thought " + System.out.println ("Some people get lost in thought " + "because it's unfamiliar territory."); "because it's unfamiliar territory."); } // method message } // method message } // class Thought

69 69 Class Advice extends Thought /*************************************************** // class Advice is a child class of Thought and over rides the parent version of Advice /*************************************************** class Advice extends Thought { public void message() public void message(){ System.out.println ("Avoid cliches like the plague."); System.out.println ("Avoid cliches like the plague."); } // method message } // method message } // class Advice

70 70 class Messages2 { public static void main (String[] args) public static void main (String[] args){ Thought Territory = new Thought(); Thought Territory = new Thought(); Advice Cliche = new Advice(); Advice Cliche = new Advice(); // call the message method in each class // call the message method in each class Territory.message(); Territory.message(); Cliche.message(); Cliche.message(); // Territory & Cliché now point to same address Territory = Cliche; Territory = Cliche; // the message method from the Advice class is printed Territory.message(); Territory.message(); } // method main } // class Messages

71 71Polymorphism  In general, it is the type of the object being referenced determines which method is invoked.   Objects of Thought class and Advice class are instantiated. They both contain a method called message.  Initially, they each call their respective methods. Then the Thought object is assigned the value of theAdvice object.

72 72Polymorphism  When the message method is invoked by the Thought object, the advice version is executed.  Note that, if an invocation is in a loop, the exact same line of code could execute different methods at different times.  Before the JDK 1.5, all polymorphic references were resolved at run-time because it may not be known what the type is until then.  However, with the new JDK1.5, there is a way to do it at compile time which we will discuss later.

73 73 Final Methods  A final method cannot be overridden.  Declaring a method final prevents the derived class from erroneously redefining a class method.  Declaring a method final allows the compiler to perform inline optimization.  final classes cannot be extended.

74 74 Class Hierarchies  A child class of one parent can be the parent of another child, forming class hierarchies Business RetailBusinessServiceBusiness KMartMacysPenny’s


Download ppt "1Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and promotes reuse  We will focus on:"

Similar presentations


Ads by Google