Inheritance - PowerPoint PPT Presentation

1 / 92
About This Presentation
Title:

Inheritance

Description:

Class hierarchies often have to be extended and modified to keep up with changing needs * Single vs. Multiple Inheritance Java supports single inheritance, ... – PowerPoint PPT presentation

Number of Views:39
Avg rating:3.0/5.0
Slides: 93
Provided by: JOHNL210
Category:
Tags: inheritance | java

less

Transcript and Presenter's Notes

Title: Inheritance


1
Inheritance
  • Inheritance is a fundamental object-oriented
    technique is 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
Encapsulation
  • By creating a class e.g. Student - and storing
    in that class all the variables and methods
    associated with a student in our program we are
  • Encapulating within the Student class all data
    pertaining to a student
  • Thus later changes to a student profile can all
    be done in one place in class

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

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

6
UML OR Unified Modeling Language is used in to
model an applicationS structures, behavior and
even business processes
PARENT
Child
PARENT CHILD RELATIONSHIP
7
Inheritance
  • As the name implies, the child inherits
    characteristics of the parent.
  • That is, 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.

8
Inheritance
  • Inheritance relationships are shown in a UML
    class diagram as 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

9
Inheritance
  • Class Car is a subclass of Vehicle and it
  • inherits state and behavior and from its parent
  • An objects state is in the form of instance
    variables and
  • its behavior in the form of methods.
  • The child inherits both from all of its
    ancestors.

10
Class Vehicle extends Object // data //
methods ( functions) Class Car extends
Vehicle // data - // methods (
functions) //some data and methods can be
inherited from Vehicle
11
Inheritance
ClassVehicle Method 1 Method 2 Method 3
Class Car Inherits all of the above methods and
can add methods of its own
12
Inheritance
  • A programmer can tailor a child class as needed
    by adding new variables or methods,
  • or by modifying the inherited ones
  • Software reuse is the fundamental benefit of
    inheritance

13
CODE REUSE
  • 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

14
Class Account deposit()
Class SavingsAccount Inherits deposit ()
Class SeniorAccount Inherits deposit()
15
Inheritance
  • This leads to smaller and easier to understand
    systems.
  • WHY?
  • Class components can be reused, promoting the
    concept of code reusability.

16
Inheritance
  • Inheritance cuts redundancy as descendant classes
    only implement functionality that is particular
    to them.
  • ///MOST IMPORTANT
  • When changes are made on the parent information,
    all child classes automatically are changed also.
  • .

17
CODE REUSE
  • Thus the models that are created are
  • easier to modify and
  • easier to implement

18
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
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 Dictionary extends Book
  • A Java class can have only one direct superclass.

20
Sub or Child Classes
  • class ParentClass // the super class
  • protected int num // instance variable
  • public ParentClass(int num) // constructor
  • this. num num

21
  • class ParentClass
  • protected int num // instance variable
  • 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
INHERITANCE
  • TO create an instance of the Childclass we use
  • Childclass child new Childclass( 20, 30)
  • This code call the parent class constructor and
    sends it two parameters which are integers that
    will be stored in newnum and
    num1
  • ( header for the Parent Class constructor)
  • public ParentClass(int newnum, float num1)

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

24
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

25
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 that helps
    in inheritance situations protected

26
The protected Modifier
  • The protected visibility modifier allows a member
    of a base class to be inherited into the child
    class
  • The protected visibility modifier provides more
    encapsulation than public does.
  • Encapsulation requires that we protect as much as
    possible our instance variables from outside
    access.

27
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

28
  • //------------------------------------------------
    -------------------
  • 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

29
Class Words
  • //
  • // Instantiates a child class and invokes 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 "

30
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
  • Answer The default constructor is called if a
    class has no coded constructor. This happens
    when instance variables already have a value.

31
The super Reference
  • Constructors are not inherited, even though they
    have public visibility !!!!
  • Yet we often need to call the parent's
    constructor to give values to the instance
    variables in the parent class
  • The super reference refers to the parent class,
  • It calls the parent class constructor.

32
  • //------------------------------------------------
    ----------
  • // Class Book s constructor initializes pages
  • //------------------------------------------------
    ------------
  • 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

33
  • ////
    //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

34
  • //
  • // Class Dictionary demonstrates the interaction
    between the constructors of parent and child
    classes.
  • //
  • class Dictionary2 extends Book 2
  • private int definitions
  • //
  • // 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 the number of pages
  • super (num_pages)
  • definitions num_definitions // sets of
    definitions
  • // constructor Dictionary

35
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

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

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

38
Class Diagram for Words
39
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.

40
SUPER and Constructors
  • This insures that the parent classs 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.

41
Key Terms to Review
  • Visibility modifiers protected
  • The Super Reference

42
Super Reference - A review
  • When we create the constructor for a child class,
    we invoke the constructor for the super class.
  • Do this in the first line of the sub class
    constructor
  • The parameter list must match the parameters in
    the argument list of the superclass
    constructor.e.g.


  • super(num_pages) // initializes the of
    pages in parent class

43
  • OVERLOADED CONSTRUCTORS
  • We might have a constructor for a Rectangle class
    with one parameter
  • public Rectangle(int width)
  • .. Initialize instance variables

44
Overloaded Constructors
  • Another constructor that could be defined by
    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,
    but they have different parameter lists.

44
45
OVERLOADED CONSTRUCTORS
  • The compiler determines which constructors to use
    based on the number and types of the parameters
    to the constructor. E.g
  • // uses constructor with one parameter
  • Rectangle rect new Rectangle(20)
  • Rectangle rect2 new Rectangle(20,30)
  • Each Rectangle object, rect and rect2, call a
    different constructor

46
Overloading Methods similar to overloaded
constructors
  • 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.

46
47
Method Overloading
  • The compiler must be able to determine which
    version of the method is being invoked by
    analyzing the parameters.
  • The return type of the method is not part of the
    signature

48
Overloading Methods
48
49
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)

49
50
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.
  • A child can redefine a method it inherits from
    its parent.

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

52
  • //
  • // 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

53
  • //
  • // Class Advice overrides the message method.
  • //but 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

54
  • ///
  • // 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

55
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

56
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
    version but
  • Implements it differently from the parent class

57
Overriding Methods
  • MOST IMPORTANT!!!!
  • 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 - same argument list

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

59
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
  • This causes Collisions, such as the same
    variable name in two parents, have to be resolved

60
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
  • The Object class is therefore the
  • ultimate root of all class hierarchies

61
The Object Class
  • The Object class contains a few useful methods,
    which are inherited by all classes, e.g.
  • The toString method in the object class prints
    out the name of the class and its memory address
  • We override the toString method in OUR classes to
    output the instance variables in OUR class

62
Class Object
  • The class Object defines the following methods
  • clone()
  • equals(Object obj) -- we use
  • finalize()
  • getClass() - we use
  • hashCode() - 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
    (same name, different formal argument lists).

63
Class Object
  • Because every class is either a direct or
    indirect subclass of Object, every class in Java
    inherits these eleven methods.
  •  
  • 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.
  •  

64
The super Reference Revisited
  • A method in the parent class can be invoked
    explicitly using the super reference
  • To call a method in the parent class, the syntax
    is
  • super.method(parameters)

65
  • 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
  • (cond)

66
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
  • (cond)

67
  • //method to compare two objects
  • // Uses String class equals method to do
    comparison
  • // String class overrides Object class equals
    method
  • public boolean equals(Object other)
  • boolean result false
  • if (LastName.equals(((Student)other).LastName)
    )
  • result FirstName.equals(((Student)other
    ).FirstName)
  • return result

68
  • public class GradStudent extends Student
  • private String source // instance variables
  • private double rate
  • //-----------------------------------------------
    -----------
  • // Sets up the gradate student using the
    specified
  • // information. Parameter include values for
  • // parent class instance variable
  • //------------------------------------------------
    -------------
  • 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 classs instance variables
  • this.source source
  • this.rate rate

69
ToString method
  • //------------------------------------------------
    -----------------
  • // Returns a description of this graduate
    student as a string. uses super to call parent
    class toString()
  • //------------------------------------------------
    -----------------
  • public String toString ()
  • // call parent class toString method and
    store in result
  • String result super.toString()
  • result "\nSupport source " source
    "\n "Hourly pay rate " rate
  • return result

70
  • 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,Govt, 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.")

71
REVIEW
  • What is overloading - for Constructors, for
    class methods
  • What is overriding
  • How do they differ
  • What does equals method in Object class do.
  • What does equals method in your class do
  • What does toString method in Object class return
  • What does toString method implemented in your
    class return

72
Polymorphism
  • 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 has a child
    class called Christmas,
  • then a Christmas reference could actually be
    declared to be a Holiday object. CONFUSING?

73
References and Inheritance
  • I can do
  • Holiday day new Holiday()
  • Christmas day new Christmas()

OR Holiday day day new Christmas()
OR Holiday day new Christmas()
74
References and Inheritance
  • Assigning a child object to an ancestor reference
    is considered to be a widening conversion,
    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

75
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

76
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).

77
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.
  • Also, assigning a child class object to a parent
    class object
  •  

78
Polymorphism
  • Some forms of polymorphism
  •  Method overloading
  • Method overriding through inheritance
  • Widening conversions
  • Polymorphism through inheritance

79
Polymorphism via Inheritance
  • A polymorphic reference is one which can refer to
    different types of objects at different times.
  • Inheritance can 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

80
Class Account
balance double
deposit() double
withdraw() double
Class Senior Savings
deposit() double Overrides parent version
Inherits other parent methods and variables
81
  • public class Accounts
  • // instance variables
  • // two methods
  • // public void deposit( double amount)
  • public void withdraw (double amount)
  • // close class
  • class SeniorSavings class extends Accounts
  • // overrides deposit in parent class
  • public void deposit (double amount)

82
  • We create an array of Accounts objects.
  • Accounts customer new Accounts10
  • E.g.
  • We create an object of the Senior_Savings class
  • Senior_Savings Sam new Senior_Savings(Sam)
  • We store Sam , a Senior_Savings object in the
    Accounts array
  • customer5 Sam

83
Polymorphism
  • We create an Accounts object called Ricky and
    store it in the array
  • Accounts Ricky new Accounts(Ricky)
  • customer3 Ricky
  • So the array of class Accounts holds both
    Senior-Savings and regular Accounts because the
    two classes are related by inheritance.
  • This is a polymorphic assignment

84
  • public class Bank
  • public static void main(String args)
  •   Account customer new Account10
  • for (int i0 ilt 3 i)

  • System.out.print ("Name of customer)
  • String name scan.next()
  • System.out.print ("Type of Account S for
    Senior, R for regular ")

  •   String type scan.next()
  •  
  • if(type.charAt(0) 'S')
  • customeri new Senior_Savings(Name,
    acctype,accountnumber)







  • else if (acctype 'R)

  • customeri new Account(Name, acctype,
    accountnumber)

  •   // close for
  •  

85
  • When we call the deposit method in a loop ,
  • the deposit method that is called depends on
    whether the object in the array
  • belongs to the Account class or the
    SeniorSavings class.

86
Polymorphism
  • if(acctype 'S')


  • customeri new SeniorSavings(name,
    acctype, accnum)
  • customeri.deposit(45) // SeniorSavings
    version called






  • else if (acctype
    'R)
  • customer i new Account(name, acctype,
    acctnum)
  • customeri.deposit(75) // Account version
    called



87
  • Lets 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

88
Class Thought
  • // Class Thought has one method
  • /
  • class Thought
  • public void message()
  • System.out.println ("Some people get lost
    in thought "
  • "because it's
    unfamiliar territory.")
  • // method message
  • // class Thought

89
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()
  • System.out.println ("Avoid cliches like the
    plague.")
  • // method message
  • // class Advice

90
  • class Messages2
  • public static void main (String args)
  • Thought Territory new Thought()
  • Advice Cliche new Advice()
  • // call the message method in each class
  • Territory.message() //
  • Cliche.message()
  • // Territory Cliché point to same address
    they are aliases
  • Territory Cliche
  • // the message method from the Advice class is
    printed
  • Territory.message() //Territory now refers
    to the Cliché class
  • // method main
  • // class Messages

91
Final Methods
  • A final method cannot be overridden or
    extended.
  • 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.

92
Class Hierarchies
  • A child class of one parent can be the parent of
    another child, forming class hierarchies
Write a Comment
User Comments (0)
About PowerShow.com