Inheritance - PowerPoint PPT Presentation

1 / 36
About This Presentation
Title:

Inheritance

Description:

... to offer an account with overdraft protection, where the customer can reduce ... check to see if the withdrawal will take the balance beyond the overdraft limit. ... – PowerPoint PPT presentation

Number of Views:52
Avg rating:3.0/5.0
Slides: 37
Provided by: alanwi8
Category:

less

Transcript and Presenter's Notes

Title: Inheritance


1
Inheritance
  • Inheritance is the ability to specify a new class
    in terms of another class.
  • In particular, only the modifications to the
    original class are specified.
  • Terminology
  • The original class is referred to as the
    superclass or parent class.
  • The new class is referred to as a subclass or
    child class.
  • Java keyword extends

2
Inheritance (2)
  • When a class is declared to be a subclass of a
    parent class, the subclass immediately has
  • all instance variables of the parent
  • all methods of the parent
  • The subclass can then specify modifications
  • additional instance variables
  • additional methods
  • modified versions of the methods in the parent
    class
  • The subclass can NOT remove instance variables or
    methods defined by the parent class.

3
When to use Inheritance?
  • Inheritance is tricky! It should be used with
    care.
  • If you can answer yes to the following
    question, then inheritance may be useful
  • A (class 2 object) IS A (class 1).
  • Example A mortgage is a loan yes.
  • Therefore mortgage could be a subclass of
    loan.
  • If you can answer yes to the following
    question, do NOT use inheritance
  • A (class 2 object) HAS A (class 1).
  • Example A bank account has a balance.

4
Example (1)
  • Suppose that we have a class BankAccount that has
  • Instance variables
  • private double balance
  • Methods
  • deposit(double amount)
  • withdraw(double amount)
  • This method checks to see if the withdrawal will
    reduce the balance below zero.
  • getBalance()
  • setBalance( double newBalance )
  • Constructor
  • BankAccount(double initialBalance)
  • Sets the initial balance

5
Example (2)
  • The bank would now like to offer an account with
    overdraft protection, where the customer can
    reduce the balance to a specified negative level.
  • Differences from a regular bank account
  • New instance variable limit
  • This is the amount by which a customer is
    permitted to withdraw below a zero balance.
  • Modified withdrawal( ) method
  • Instead of checking for a withdrawal that would
    reduce the balance to below zero, the method
    should check to see if the withdrawal will take
    the balance beyond the overdraft limit.
  • New class variable serviceCharge
  • The monthly fee charged to all holders of these
    accounts.
  • Otherwise, all previous properties of a
    BankAccount apply.

6
Class BankAccount
  • public class BankAccount
  • private static double rate
  • private double balance 0.0
  • public BankAccount( double initialBalance )
    / code not shown /
  • public static double getInterestRate( ) /
    code not shown /
  • public static void setInterestRate( double
    newRate ) / code not shown /
  • public double getBalance( ) / code not
    shown /
  • public void setBalance( double newBalance )
    / code not shown /
  • public void addMonthlyInterest( ) / code
    not shown /
  • public boolean deposit( double amount ) /
    code not shown /
  • public boolean withdrawal( double amount )
  • boolean result
  • if ( this.balance - amount lt 0.0 )
  • result false

7
Class OverdraftAccount
  • public class OverdraftAccount extends BankAccount
  • private static double serviceCharge
  • private double limit 0.0
  • public double getOverdraftLimit( ) / code
    not shown /
  • public void setOverdraftLimit( double
    newLimit ) / code not shown /
  • public static void setServiceCharge( double
    newRate ) / code not shown /
  • public boolean withdrawal( double amount )
  • boolean result
  • if ( this.getBalance( ) - amount lt -
    limit )
  • result false
  • else
  • this.setBalance( this.getBalance( )
    amount )

8
Whats in an OverdraftAccount?
  • Note that the OverdraftAccount still has the
    variables defined from BankAccount.
  • This means that an OverdraftAccount object
    instance has
  • Instance variables
  • balance (from BankAccount)
  • limit
  • Static variables
  • rate (from BankAccount)
  • serviceCharge
  • The OverdraftAccount also inherits the following
    methods from BankAccount
  • deposit( ), getBalance( ), setBalance( ),
    getInterestRate( ), setInterestRate( ),
    addMonthlyInterest( )
  • The OverdraftAccount also has its own version of
    the withdraw() method.

9
Comparison of objects
anOverdraftAccount
aBankAccount
1250.00
1400.00
balance
balance
(to class variables)
(to class variables)
250.00
limit
(to class variables)
0.01
5.00
serviceCharge
rate
Class BankAccount
Class OverdraftAccount
10
Constructors for a subclass
  • Suppose that you wanted to have the following
    constructor
  • public OverdraftAccount( double initialBalance,
    double initialLimit)
  • This constructor should first set up the
    BankAccount part, and then finish constructing
    the OverdraftAccount.
  • public OverdraftAccount( double initialBalance,
    double initialLimit)
  • super( initialBalance ) // Calls
    BankAccount constructor
  • // to set the
    value of balance
  • this.limit initialLimit

11
super
  • The reference super refers to the superclass of
    any object
  • It is set automatically, just like this
  • It can be used to call the superclass version of
    a method
  • For example, inside the withdraw method in the
    class OverdraftAccount, there could be
  • super.withdraw( amount )
  • if this was an appropriate task to do.
  • It can also be used to call a constructor
  • super( initialBalance )
  • (must be the first line in a subclass
    constructor)

12
Access to superclass instance variables
  • Recall that the definition of private access is
    that only code within the class can access the
    variable or method.
  • This applies to subclasses they are NOT part of
    the parent class.
  • Therefore, within the class OverdraftAccount,
    there is no direct access to the variable
    balance.
  • Notice that the withdraw() method in
    OverdraftAccount used getBalance() and
    setBalance() instead of this.balance. This is
    because the methods are public, while the
    variable is private.

13
protected access
  • There is another level of access control, that
    restricts access to within the class OR any
    subclasses protected
  • For example, we could change the access level of
    the variable balance in class BankAccount to
    protected, and then it could be accessed also
    within the class OverdraftAccount
  • protected double balance 0.0
  • It is also possible to have protected methods.

14
Variables and subclasses
  • It is possible to assign a subclass object to a
    variable which has the type of its superclass
    (but NOT the other way around!)
  • Example
  • BankAccount anAccount new OverdraftAccount()
    // OK
  • OverdraftAccount a2 new BankAccount( ) //
    error
  • While assigned to such a variable, the
    OverdraftAccount object will appear as if it were
    a BankAccount object
  • This means that you can call BankAccount methods,
    but NOT OverdraftAccount methods using the
    variable anAccount.
  • anAccount.getBalance( ) // OK
  • anAccount.setOverdraftLimit( ) // error

15
Variables and subclasses (2)
  • Using this property, you could process all bank
    accounts without regard as to whether they are
    regular accounts or overdraft account.
  • For example, you could go through a collection of
    accounts and add the monthly interest to each
    account.

16
The class Object
  • All classes, unless otherwise specified, are
    direct subclasses of the class Object (from the
    Java software development kit)
  • The class Object has some methods that are rarely
    used, but can be called on any object.
  • The more useful property is the following if
    you declare a variable to be of type Object, you
    can assign a reference to ANY object to this
    variable
  • This is useful (for example) for creating
    collections of objects.

17
Example Class ArrayList
  • The Java software development kit provides a set
    of collection classes that are more flexible
    than arrays.
  • One useful class is called ArrayList.
  • Like arrays, they are indexed by position number
    from 0 up to the maximum position 1.
  • However, it is easy to add new items to the
    collection (at the end, or inserting into the
    middle) or to remove items from the collection.

18
ArrayList methods
  • add(Object o)
  • Adds an item to the end of the collection.
  • add(int index, Object element)
  • Adds an item to the collection at position index.
    Items at position index or higher are shifted to
    the right.
  • remove(int index)
  • Removes the item at position index. Items at
    position index1 or higher are shifted to the
    left.
  • int size()
  • Returns the number of items in the collection
  • Object get(int index)
  • Returns the item at position index.
  • set(int index, Object element)
  • Replaces the item at position index with the
    specified item.

19
ArrayList methods
  • If the objects in the ArrayList have implmented
    theboolean equals(Object o) method
  • boolean contains(Object elem)
  • Returns true if the object elem is contained in
    the ArrayList
  • int indexOf(Object elem)
  • Returns the position where the object elem is
    contained in the ArrayList, or -1 if it is not
    there.

20
Two caveats for using ArrayList
  • The return type of get is an Object.
  • You will have to use casting to recover the
    original object type, which means you may need to
    keep track of what type of object is contained in
    the ArrayList.
  • You cant directly store primitive types in an
    ArrayList because they arent subclasses of
    Object.
  • However, the wrapper classes Integer, Boolean,
    Double, etc. ARE subclasses of Object, and they
    can be stored in the collection.

21
Subclasses and Superclasses
  • All classes from a part of a class hierarchy.
  • Every class except Object is a subclass of some
    other class, and it inherits instance variables
    and methods from its parent class.
  • The class can add additional instance variables
    and methods, and can also override the behavior
    of methods inherited from its parent class.
  • Any class above a specific class in the class
    hierarchy is a superclass of that class.
  • Any class below a specific class in the class
    hierarchy is a subclass of that class.

22
Defining Superclasses and Subclasses
  • Methods and instance variables defined in class
    Employee are inherited by the two subclasses
  • Because of inheritance, objects of the
    Salaried-Employee and Hourly-Employee classes are
    also objects of the Employee class

23
Creating Subclasses
  • A subclass is defined using the extends keyword
    to indicate that it inherits from a superclass
  • public class SalariedEmployee extends Employee
  • The subclass then inherits all non-private
    instance variables and methods from its parent
    class
  • Instance variables in class Employee should be
    declared protected so that they are visible to
    subclasses but not to the outside world
  • Methods inherited from the superclass can be
    overridden in the subclass to change behaviors

24
Constructors in Subclasses
  • When a object of a subclass is instantiated, a
    constructor for its superclass is called either
    implicitly or explicitly before any other
    initialization is performed

Implicit call to default constructor Employee()
before line 20
Explicit call to Employee(first, last, ssn)
25
Treating Subclass Objects as Superclass Objects
  • Since an object of a subclass is also an object
    of its superclass, the object can be addressed
    with either subclass or superclass references.
  • This means that objects of many different
    subclasses can be combined and manipulated as
    objects of a single superclass.

26
Treating Subclass Objects as Superclass Objects
(2)
Objects created with subclass references
Objects used with subclass references
Objects used with superclass references
27
Polymorphism (1)
  • If a superclass declares a method method1, then
    all subclasses of the class will inherit the
    method.
  • Each subclass can override the inherited method
    to provide its own imple-mentation, but they will
    all have a method with the inherited methods
    name and calling parameters.

Defines method1
Overrides method1 with a new definition.
Overrides method1 with a new definition.
28
Polymorphism (2)
  • If objects of the subclasses are treated as
    objects of the superclass, and if method1 is
    called by one of the objects, then the version of
    method1 called will automatically be the correct
    one for the subclass that the object belongs to.
  • This behavior is called polymorphism, meaning
    many forms.
  • Objects of many types can be processed together,
    with the individual behaviors automatically
    correct for each object.

29
Abstract Classes
  • If a particular method is overridden in all
    subclasses of a superclass, and if only objects
    of the subclasses are to be created, the method
    code in the superclass will never be executed.
  • If so, then why write the method code in the
    superclass at all?
  • The method header in the superclass is required
    for polymorphic behavior, but the body of the
    method is useless.
  • We can declare the superclass method header
    without writing the method body. The method
    becomes an abstract method.
  • A class containing one or more abstract methods
    is an abstract class.

30
Abstract Classes
  • An abstract method or class is declared with the
    abstract keyword
  • public abstract double calcPay( double hours )
  • No object can be instantiated from an abstract
    class
  • Every subclass of an abstract class that will be
    used to instantiate objects must provide
    implementations for all abstract methods in the
    superclass.
  • Abstract classes save time, since we do not have
    to write useless code that would never be
    executed.

31
ExampleA Shape Class
Superclass contains abstract methods area and
perimeter.
Subclasses implement concrete methods area and
perimeter.
32
ExampleA Shape Class
Superclass definition. Note class is declared
abstract.
Abstract method definitions. Note only header is
declared. These methods must be overridden in
all concrete subclasses.
33
ExampleThe Circle Subclass
Concrete class. Class must not contain or inherit
abstract methods. Inherited abstract methods
must be overridden.
Concrete method definitions. Note that the method
body is declared here.
34
ExampleThe Triangle Subclass
Concrete class. Class must not contain or inherit
abstract methods. Inherited abstract methods
must be overridden.
Concrete method definitions. Note that the method
bodies are different from those in Circle, but
the method signatures are identical.
Other subclasses of Shape will also override the
abstract classes area and perimeter.
35
ExampleClass TestShape
Create objects of subclasses using superclass
references.
Call area and perimeter methods. The proper
version of each method will be automatically
called for each object.
36
ExampleExecuting TestShape
Note that the area and perimeter were calculated
properly for each type of object.
Write a Comment
User Comments (0)
About PowerShow.com