Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inheritance  Inheritance is a fundamental object-oriented technique  it enhances software design and promotes reuse  We will focus on:  deriving new.

Similar presentations


Presentation on theme: "Inheritance  Inheritance is a fundamental object-oriented technique  it enhances software design and promotes reuse  We will focus on:  deriving new."— 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 1

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

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

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

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

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

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, or base class  The derived class  The derived class is called the child class or subclass. 7

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

9 Inheritance  The child inherits characteristics of the parent. methods and data  The child class inherits the methods and data defined in the parent class  This means that all child classes have access to the methods and data. 9

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

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

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

13 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 fundamental benefit of inheritance  Software reuse is the fundamental benefit of inheritance 14

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

16 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.. 17

18 CODE REUSE  Thus the models that are created are :  easier to modify and  easier to implement 18

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

20  T he reserved word extends 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. 20

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

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

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? 23

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? 24

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

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

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 27

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 28

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

30 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 31

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 32

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: " “ # of definitions: 52500/1500 Definitions per page: " 33

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 34

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

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

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

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(int num_pages) { pages = num_pages; // sets number of pages } // constructor Book } // class Book2 38

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 39

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 (int num_pages, int num_definitions) { // “super” calls parent class constructor and sends it the number of pages super (num_pages); definitions = num_definitions; // sets # of definitions } // constructor Dictionary 40

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 41

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 42

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 ? 43

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

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

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

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

48 Super Reference - A review  When we create the constructor for 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) 48

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

50 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 } share the same name,  Both constructors share the same name,  Rectangle(variables)  but they have different parameter lists.

51 OVERLOADED CONSTRUCTORS  The compiler determines which constructors to use based on the  number and types of the parameters to the constructor.  E.g  // calls a constructor with one parameter  Rectangle rect = new Rectangle(20);   // requires a constructor with two parameters  Rectangle rect2 = new Rectangle(20,30); 51

52 Overloaded constructors  // calls a constructor with one parameter  Rectangle rect = new Rectangle(20);   // requires a constructor with two parameters  Rectangle rect2 = new Rectangle(20,30);  Each Rectangle object, rect and rect2, call a different constructor 52

53 53 Overloading Methods – similar to overloaded constructors  Method overloadingis the process of using the same method name for multiple 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.

54 Method Overloading  The compiler determines the version of the method being invoked by : analyzing the parameters.  The return type of the method is  not part of the signature! 54

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

56 56 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);

57 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. can redefine a method  A child class can redefine a method it inherits from its parent. 57

58 Overriding Methods  The new method must have the same signature as the parent's method,  but can have different code in the body  Same signature = same number and type of parameters etc. 58

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

60 //------------------------------------------------------------------------ // Class Advice overrides the message method. // it keeps same method name and number of parameters //____________________________________________ class Advice extends Thought { // This method overrides the parent version, public void message() { System.out.println ("Warning: Dates in calendar are " + "closer than they appear."); } // method message } // class Advice 60

61 ///********************************************** // 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 Advice dates = new Advice();// create Advice object parked.message(); // calls method in Thought class dates.message(); // calls method in Advice class } // method main } // class Messages 61

62 Overloading vs. Overriding  Don't confuse the concepts of overloading and overriding  Overloading : deals with multiple methods in the same class  W ith the same name but with different signatures 62

63 Overriding vs Overloading  Overriding deals with two methods,  one in a parent class and  one in a child class,  That both have the same signature 63

64 Overloading VS Overriding  Overloading lets you define a method in different ways  for different data in the same class  Overriding lets you define a method in a child class  that has the same signature as the parent class  But  Implements it differently from the parent class 64

65  MOST IMPORTANT!!!!  To overload a method in the same class  You must duplicate the method name,  but use a different argument list. 65

66 OverRiding a method  To override a method,  you must match the entire method signature -  same argument list  AND The method overridden is in the parent class 66

67 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 possible. 67

68 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’ classes  This causes “Collisions”, such as the same variable name in two parents, have to be resolved 68

69 The Object Class  The class Object is defined in the java.lang package of the Java standard class library  All classes are derived from the Object class Object class  The Object class is therefore the  ultimate root of all class hierarchies 69

70 The Object Class  The Object class contains a few useful methods,  inherited by all classes, e.g.  The toString method in the object class : 1. prints out the name of the class and 2. its memory address (hexadecimal representation of the hash code of the object)  We override the toString method in OUR classes to output the instance variables in OUR class 70

71 71 Class Object  The class Object defines the following methods: clone() --we use equals(Object obj) -- we use finalize() getClass() - we use hashCode() - we use sometimes notify() notifyAll() toString() -- we use wait() wait(long timeout) wait(long timeout, int nanos)  As you can see, this list includes three overloaded versions of the method named wait

72 Class Object  Because every class is direct or indirect subclass of Object  either a direct or indirect subclass of Object, inherits these eleven methods.  every class in Java inherits these eleven methods.  Many of these eleven methods are intended to be overridden for various purposes. getClass, notify, and wait, to be used directly without overriding.  However, some of them, such as getClass, notify, and wait, are intended to be used directly without overriding. 72

73 The super Reference Revisited  A method in the parent class can be invoked explicitly using super.methodName(parameters)  To call a method in the parent class, the syntax is: super.method(parameters) 73

74 public class Student { protected String Firstname, Lastname; protected int numCourses; //----------------------------------------------------------------- // Sets up a student with a name and number of courses. //----------------------------------------------------------------- public Student (String Firstname, String Lastname, int numCourses) { this.Firstname = Firstname; this. Lastname = LastName this.numCourses = numCourses; } (con’d) 74

75 To String method //----------------------------------------------------------------- // Returns information about this student as a string. // Used in System.out.println calls – typical toString //----------------------------------------------------------------- public String toString () { String result = "Student name: " + Firstname + “ “ + Lastname "\n"; result += "Number of courses: " + numCourses; return result; } (con’d) 75

76 //method to compare two objects // Uses String class equals method to do comparison // String class overrides equals method of Object class public boolean equals(Object other) { boolean result = false; if (LastName.equals(((Student)other).LastName)) result = FirstName.equals(((Student)other).FirstName); return result; } } 76

77 public class GradStudent extends Student { private String source; // instance variables private double rate; //---------------------------------------------------------- // Sets up the gradate student using the specified information. Parameters include values for parent class instance variables //------------------------------------------------------------- public GradStudent (String Fastname, String LastName, int numCourses, String source, double rate) { // call parent class constructor to initialize its instance variables super (Firstname, Lastname, numCourses); // initalize this class’s instance variables this.source = source; this.rate = rate; } 77

78 ToString method //----------------------------------------------------------------- // Returns a description of this graduate student as a string. – uses super to call parent class toString() and adds some data declared in this class //----------------------------------------------------------------- public String toString () call parent class toString method and store in “result” { // call parent class toString method and store in “result” String result = super.toString(); // add instance variables of this class to “result” result += result += "\nSupport source: " + source + "\n” + "Hourly pay rate: " + rate; return result; } } 78

79 class Academia { //---------------------------------------------------- // Creates objects of two student types, prints some //information about them, then checks them for equality. //----------------------------------------------------- public static void main (String[] args) { Student susan = new Student ("Susan", “James”, 4); GradStudent Paul = new GradStudent ("Paul",”McCartney”, 1,“Gov’t”, 10.00); System.out.println (susan); // uses toString method in Student System.out.println (Paul); // uses toString method in GradStudent // calls equals method in Student which compares last and first names - if (!susan.equals(Paul)) System.out.println ("These are two different students."); }} 79

80 OUTPUT FOR Susan & Paul From the toString method in Student class for object Susan toString() { "Student name: " + Firstname + “ “ + Lastname "\n"; result += "Number of courses: " + numCourses; Output FOR SUSAN: Susan James Number of courses 4 From the toString method in gradStudent for object Paul toString (){ // invokes parent class toString)( see above) String result = super.toString(); // invokes parent class toString)( see above) // concatenate instance variables of this class to “result” result += result += "\nSupport source: " + source + "\n” + "Hourly pay rate: " + rate; return result; } Output for GradStudent PAUL Paul McCartney Number of courses 1 Support source Gov’t Hourly pay Rate 10.00 80

81 Grad Student uses parent to String()  So the grad student class makes use of the toString method in the parent class  AND adds new values particular to  the GradStudent class. 81

82 REVIEW  What is overloading - for  Constructors AND class methods  What is overriding  How do they differ  What does equals method in Object class do.  What does equals method DO in child classes  What does toString method in Object class return  What does toString method implemented in your class return 82


Download ppt "Inheritance  Inheritance is a fundamental object-oriented technique  it enhances software design and promotes reuse  We will focus on:  deriving new."

Similar presentations


Ads by Google