Chapter 11 Inheritance

1 / 69
About This Presentation
Title:

Chapter 11 Inheritance

Description:

private double battingAvg; public static void printOrigins ... private double salary; ... The end. Creating a Subclass Method that Overrides a Superclass Method ... – PowerPoint PPT presentation

Number of Views:49
Avg rating:3.0/5.0
Slides: 70
Provided by: burns9
Learn more at: http://burns.ba.ttu.edu

less

Transcript and Presenter's Notes

Title: Chapter 11 Inheritance


1
Chapter 11 -- Inheritance
  • Jim Burns

2
The Concept of Inheritance
  • Since day one, you have been creating classes and
    instantiating objects that are members of those
    classes.
  • Programmers use a graphical language to describe
    classes and object-oriented processesthis
    Unified Modeling Language consists of many types
    of diagrams

3
Class diagram
  • Is a visual tool that provides you with an
    overview of a class
  • It is a rectangle divided into three sections
  • the top section contains the name of the class
  • The middle section contains the names and data
    types of the attributes
  • The bottom section contains the methods

4
The Employee class diagram
5
Another employee class
  • Suppose that a new employee called serviceRep is
    hired and that, in addition to employee number
    and salary, he needs a territory.
  • Rather than creating a whole new class, you can
    create a new class that inherits the behaviors
    and attributes of the original employee class
  • This is reuse at its best

6
(No Transcript)
7
When you use inheritance you
  • Save time because the Employee fields and methods
    already exist
  • Save money because it takes less time to create a
    class that uses structure in old classes
  • Reduce errors because the Employee methods
    already have been used and tested
  • Reduce the amount of new learning required to use
    the new class, because you have used the Employee
    methods on simpler objects and already understand
    how they work

8
Base classes
  • Classes from which other classes inherit
    attributes or methods
  • Classes that inherit from base classes are called
    derived classes
  • A base class is also called a superclass
  • A derived class is also called a subclass
  • You can also use the terms parent class and child
    class

9
  • public class ASubClass extends ASuperClass
  • public ASubClass()
  • System.out.println("In subclass
    constructor")

10
  • public class ASuperClass
  • public ASuperClass()
  • System.out.println("In superclass
    constructor")

11
Extending Classes
  • You use the keyword extends to achieve
    inheritance in Java
  • Example
  • Public class EmployeeWithTerritory extends
    Employee
  • You used the extends JApplet throughout Chapters
    9 and 10every JApplet that you wrote is a child
    of the JApplet class

12
Object instantiation
  • You instantiate an object with a statement such
    as
  • employeeWithTerritory northernRep new
    EmployeeWithTerritory()
  • Inheritance is a one-way propositiona child
    inherits from a parent, not the other way around
  • For example an employee object cannot inherit
    from the employeeWithTerritory subclasscant
    access its methods

13
Getting field values from an object
  • You can use any of the next statements to get
    field values for the northernRep object
  • northernRep.getEmpNum()
  • northernRep.getEmpSal()
  • northernRep.getEmpTerritory()

14
After the northernRep object is declared
  • Any of the following statements are appropriate
  • northernRep.setEmpNum(915)
  • northernRep.setEmpSal(210.00)
  • northernRep.setEmpTerritory(5)
  • The northernRep object has access to all the
    parent Employee class set methods, as well as its
    own classs new set method

15
Child classes are more specific
  • An Orthodontist class and Periodontist class are
    children of the Dentist parent class.
  • The Dentist class does not have a Orthodontists
    applyBraces() method or the Periodontists
    deepClean() method.
  • However, Orthodontist objects and Perodontist
    objects have access to the more general Dentist
    methods

16
Instanceof
  • Instances of child classes are also instances of
    the parent classes of that class
  • The following are true
  • If(myOrthodontist instanceof Dentist)
  • If(myOrthodontist instanceof Orthodontist)

17
Overriding Superclass Methods
  • When you extend a superclass, you create a
    subclass that inherits the superclass attributes
    and methods
  • What do you do if you do not want these
    attributes and methods?
  • You can write your own
  • In the musical instruments world a play() method
    would be very different for a guitar as compared
    to a drum
  • This is called polymorphism

18
Polymorphism
  • Literally means many forms
  • Consider an employee superclass with a
    printRateOfPay() method
  • For weekly employees the print statement might be
  • System.out.println(Pay is rateOfPay per
    week)
  • For hourly employees the print statement might be
  • System.out.println(Pay is rateOfPay per
    hour)

19
What do you do?
  • When you create a method in a child class that
    has the same name and argument list as a method
    in its parent class, you override the method in
    the parent class
  • When you use the method name with a child object,
    the childs version of the method is used

20
As an alternative
  • You could create and use a method with a
    different name
  • But the classes are easier to write and
    understand if you use one reasonable name for
    methods that do essentially the same thing.
  • In the example above, because we are attempting
    to print the rate of pay for each object,
    printRateOfPay() is an excellent method name for
    this function.

21
Can you think of any other reasons why
polymorphism makes sense?
  • When you have to change some aspect of behavior
    that is common to all of the classes and that
    piece of behavior is inherited, then you have to
    change it only in one placenot ten places

22
Understanding how Constructors are called During
Inheritance
  • Consider the following
  • SomeClass anObject new SomeClass()
  • Here you are instantiating an object of a
    subclass by invoking the SomeClass() constructor
  • You are actually calling at least two
    constructors the constructor for the base class
    and the constructor for the extended, derived
    class.
  • When a subclass constructor executes, the
    superclass constructor must execute first and
    then the subclass constructor

23
More
  • Often the execution of the superclass constructor
    is transparentnothing call attention to the fact
    that the superclass constructor is executing.

24
Question
  • Suppose that HourlyEmployee is a subclass of
    Employee.
  • When you create an object of HourlyEmployee
    called clerk
  • What happens in terms of the constructors
    involved???

25
  • public class ASuperClass
  • public ASuperClass()
  • System.out.println(In superclass constructor)
  • public class ASubClass extends ASuperClass
  • public ASubClass()
  • System.out.println(In subclass constructor)
  • public class DemoConstructors
  • public static void main(String args)

26
The above produces the following output at the
Command Prompt
  • C\Java\java DemoConstructors
  • In superclass constructor
  • In subclass constructor

27
Using Superclass Constructors that Require
Arguments
  • When you create a class and do not provide a
    constructor, Java automatically supplies you with
    a default constructorone that never requires
    arguments
  • When you write your own constructor, you replace
    the automatically supplied version

28
More on constructors
  • When all superclass constructors have
    constructors that require arguments, you must
    make sure the subclass constructors provide those
    arguments
  • In this case there is no default superclass
    constructor without args

29
More on constructors
  • Your subclass constructors can contain any number
    of statements, but the first statement within
    each subclass constructor must call the
    superclass constructor
  • The format for the statement that calls a
    superclass constructor is
  • super(list of arguments)

30
Accessing Superclass Methods
  • When two methods use the same name in both a
    superclass and a subclass, the sublcass method
    overrides the supperclass method.
  • When you want the superclass method to be used,
    you use the keyword super to access the
    superclass method

31
  • public class Customer
  • private int idNumber
  • private double balanceOwed
  • public Customer(int id, double bal)
  • idNumber id
  • balanceOwed bal
  • public void display()
  • System.out.println("Customer "
    idNumber
  • " Balance " balanceOwed)

32
  • public class PreferredCustomer extends Customer
  • double discountRate
  • public PreferredCustomer(int id, double bal,
    double rate)
  • super(id, bal)
  • discountRate rate
  • public void display()
  • super.display()
  • System.out.println("Discount rate is "
    discountRate)

33
  • public class TestCustomers
  • public static void main(String args)
  • Customer oneCust new Customer(124,
    123.45)
  • PreferredCustomer onePCust new
  • PreferredCustomer(125, 3456.78, 0.15)
  • oneCust.display()
  • onePCust.display()

34
Command Prompt
  • C\JavagtJava TestCustomers
  • Customer 124 Balance 123.46
  • Chstomer 125 Balance 3456.78
  • Discount rate is 0.15
  • C\Javagt

35
  • public class DemoConstructors
  • public static void main(String args)
  • ASubClass child new ASubClass()

36
Learning about Information Hiding
  • Information hiding is a way to disallow certain
    attributes and methods to be accessible within
    other classes
  • We use the keyword private to make an attribute
    or method local to the class and not accessible
    elsewhere

37
  • public class Student
  • private int idNum
  • private double gpa
  • public int getIdNum
  • return idNum
  • public double getGpa()
  • return gpa
  • public void setIdNum(int num)
  • idNum num
  • public void setGpa(double gradePoint)
  • gpa gradePoint

38
Why wont the following code work??
  • Suppose you write a main() method in another
    class that does the following
  • Student someStudent new Student()
  • someStudent.idNum 812
  • Only methods contained within the student class
    are allowed to alter Student data
  • someStudent.setIdNum(812)

39
Remember
  • The methods in a subclass can use all the fields
    (attributes, data) in an inherited superclass as
    well as its methods, except.
  • Those declared as.

private
40
This is called .
Information Hiding
41
Are there other access modifiers??
  • Yes, Virginia, there are
  • Suppose that you want data to be accessible to
    the class it was defined in as well as subclasses
    that extend that class, but not in any other
    classesthat is you dont want the data to be
    public
  • Then, you use the keyword protected

42
Using Methods you cannot Override
  • The three types of methods that you cannot
    override in a subclass are
  • static methods
  • final methods
  • Methods within final classes

43
A Subclass Cannot Override static Methods in its
Superclass
  • A subclass cannot override methods that are
    declared static in the superclass.
  • Not even with the keyword super
  • See code below in which ProfessionalBaseballPlayer
    extends BaseballPlayer

44
  • public class BaseballPlayer
  • private int jerseyNumber
  • private double battingAvg
  • public static void printOrigins()
  • System.out.println("Abner Doubleday is often
    "
  • "credited with inventing baseball")

45
  • public class ProfessionalBaseballPlayer extends
    BaseballPlayer
  • double salary
  • public void printOrigins()
  • BaseballPlayer.printOrigins()
  • System.out.println("The first professional "
  • "major league baseball game was played
    in 1871")

46
In the above two frames of code..
  • Java does not allow the printOrigins() in the
    subclass ProfessionalBaseballPlayer to override
    the static method printOrigins() in the
    superclass BaseballPlayer
  • This doesnt work even if you declare the method
    printOrigins() in the subclass ProfessionalBasebal
    lPlayer to be static, as follows

47
  • public class ProfessionalBaseballPlayer extends
    BaseballPlayer
  • double salary
  • public static void printOrigins()
  • super.printOrigins()
  • System.out.println("The first professional "
  • "major league baseball game was played
    in 1871")

48
  • However, the following code will work

49
  • public class ProfessionalBaseballPlayer extends
    BaseballPlayer
  • double salary
  • public static void printOrigins()
  • BaseballPlayer.printOrigins()
  • System.out.println("The first professional "
  • "major league baseball game was played
    in 1871")

50
When used with the following class
  • Public class TestProPlayer
  • public static void main(String args)
  • professionalBaseballPlayer aYankee new
    ProfessionalBaseballPlayer()
  • aYankee.printOrigins()

51
The following output will be produced
  • C\JavagtJava TestProPlayer
  • Abner Doubleday is often credited with inventing
    baseball
  • The first professional major league baseball game
    was played in 1871

52
A Subclass Cannot Override final Methods in its
Superclass
  • A subclass cannot override methods that are
    declared final in the superclass.
  • Consider the classes BasketballPlayer and
    ProfessionalBasketballPlayer below
  • These will generate an error at compile time

53
  • public class BasketballPlayer
  • private int jerseyNumber
  • public final void printMessage()
  • System.out.println("Michael Jordan is the "
  • "greatest basketball player - and that is
    final")

54
  • public class ProfessionalBasketballPlayer extends
    BasketballPlayer
  • double salary
  • public void printMessage()
  • System.out.println("I have nothing to say")

55
  • Public void display(BasketballPlayer bbplayer)
  • bbplayer.printMessage()
  • The above will cause the code created for
    printMessage() to be inserted inline and the
    practice is called inlining.

56
A Subclass Cannot Override Methods in a final
Superclass
  • You can also declare a class to be final
  • Then all of its methods will be final as well,
    regardless of what access modifiers precede the
    method name in the melthod header

57
  • public final class HideAndGoSeekPlayer
  • private int count
  • public void printRules()
  • System.out.println("You have to count to "
    count
  • " before you start looking for hiders")

58
  • public final class ProfessionalHideAndGoSeekPlayer
  • extends HideAndGoSeekPlayer
  • private double salary

59
  • The above two frames of code will generate a
    compiler error when you try to compile the
    ProfessionalHideAndGoSeekPlayer class.

60
The end
61
(No Transcript)
62
(No Transcript)
63
Creating a Subclass Method that Overrides a
Superclass Method
64
Understanding the role of Constructors in
Inheritance
65
Understanding Inheritance when the Superclass
Requires Constructor Arguments
66
Accessing an Overridden Superclass Method from
within a Subclass
67
Understanding the protected Access Modifier
68
(No Transcript)
69
(No Transcript)
Write a Comment
User Comments (0)