7A: Introduction to Inheritance

What We Will Cover


Continuations

Questions on What's Due Next?

Questions from last class?

7.1: Introduction to Inheritance

Objectives

At the end of the lesson the student will be able to:

  • Describe how inheritance is used in Java
  • Use inheritance in your programs
  • Inherit from Java's classes

7.1.1: Introducing Inheritance

Inheritance: ability to define new classes from existing ones.

  • Inheritance is one of the key ideas of object-oriented programming
  • Lets you define a class that inherits all the public and protected fields and methods from another class
  • Class that inherits is called the subclass (derived, child)
  • Class being inherited is called the superclass (base, parent)
  • In a subclass, define new fields and methods not found in the superclass
  • Following is a UML diagram of an inheritance example

About the Diagram

  • First section of class diagram contains the class name
  • Second section describes the attributes (data variables)
  • Bottom section describes the operations (methods)
  • Minus sign (-) marks attributes and operations that cannot be accessed by other classes
  • Plus sign (+) marks attributes and operations that can be accessed by other classes
  • Parameters are listed in parenthesis separated by commas
  • Name of the parameter is followed by a colon and the data type
  • Methods that return values are followed by a colon and the return type
  • Upward pointing arrow indicates inheritance

7.1.2: Inheritance Example

  • Deriving a new class from an existing one requires the extends clause
  • Syntax:
  • public class SubclassName extends SuperclassName
  • Subclass can only extend one superclass
    • Java does not support multiple inheritance
    • Interfaces (discussed later) achieve much of the same effect
  • Following example extends the BookOrder class we used earlier
public class DiscountBookOrder extends BookOrder {
    public final static double DISCOUNT = 0.1;
    private String discountCode;
    private double subtotal, percentOff, total;

    public DiscountBookOrder(String bookCode,
                int bookQuantity, String keyCode) {
        super(bookCode, bookQuantity);
        discountCode = keyCode;
        setPercentOff();
        setTotal();
    }

    public void setPercentOff() {
        if (discountCode.equalsIgnoreCase("a10"))
            percentOff = DISCOUNT;
        else
            percentOff = 0.0;
    }

    public void setTotal() {
        subtotal = super.getQuantity()
                * super.getBook().getPrice();
        total = subtotal - (subtotal * percentOff);
    }

    public double getSubtotal() { return subtotal; }
    public double getPercentOff() { return percentOff; }
    public double getTotal() { return total; }
}
  • Note the use of the super keyword to call the constructor of BookOrder
  • super(bookCode, bookQuantity);
  • Example also uses super keyword to call methods of the superclass
  • super.getQuantity()
  • Use of super not required since subclasses inherit all the methods of the superclass
  • Following is a driver application for the inherited class
import javax.swing.JOptionPane;
import java.text.*;

public class OverrideTest{
    public static void main(String[] args) {
        NumberFormat currency =
            NumberFormat.getCurrencyInstance();
        NumberFormat percent =
            NumberFormat.getPercentInstance();
        DiscountBookOrder order =
            new DiscountBookOrder("WARP", 2, "a10");
        String test = "Title: " + order.getBook().getTitle()
            + "\nPrice: " + order.getBook().getPrice()
            + "\nQuantity: " + order.getQuantity()
            + "\nSubtotal: "
            + currency.format(order.getSubtotal())
            + "\nPercentOff: "
            + percent.format(order.getPercentOff())
            + "\nTotal: " + currency.format(order.getTotal());
        JOptionPane.showMessageDialog(null, test);
        System.exit(0);
    }
}

7.1.3: Class Hierarchies

  • Classes can be derived from derived classes
    • Subclass objects can be treated as superclass objects
    • Child classes can be parent classes
  • Classes higher in the hierarchy called ancestor classes
  • Classes lower in the hierarchy called descendent classes
  • Note that inheritance describes an is-a relationship
    • A Dialog is a Window
  • Reverse is not true
    • Window is not always a Dialog

For Example

  • Following is taken from the Java API
  • Shows that a superclass can have more than one subclass
  • For instance, Window has two subclasses

Another Way to Draw Inheritance

  • There are many ways to draw inheritance daigrams
  • Following is another way to show the inheritance hierarchy for Container
  • Note that the superclass is always drawn higher than the subclass
  • Container
       |
       +--Panel
       |     |
       |     +--Applet
       |
       +--Window
             |
             +--Frame
             |
             +--Dialog
    
    

Designing with Inheritance

  • Note in the inheritance diagram above that a Frame is a type of Window
  • When using inheritance in an application, important to keep "is a" in mind
  • Make sure a subclass has an is-a relationship with the superclass
    • A subclass must be a type of a superclass
  • Which of the following are valid is-a relationships?
    • Car ==> vehicle
    • Car ==> motorcycle
    • Student ==> Person
    • Student ==> College
  • Substitue the words "is a type of" for the arrow (==>)

7.1.4: Inheriting From JFrame

  • To use Java libraries, will often need to use inheritance
  • One commonly extends Java while developing graphical user interfaces
  • Must understand a classes inheritance chain to use it fully
  • For instance the following is the inheritance chain for a JFrame
  • To implement a JFrame using inheritance, write code like the following
  • import javax.swing.*;
    
    public class BookOrderFrame extends JFrame {
       public BookOrderFrame(){
          setTitle("Book Order");
          setBounds(267, 200, 267, 200);
       }
    
       public static void main(String[] args) {
          JFrame frame = new BookOrderFrame();
          frame.show();
       }
    }
    
  • By extending JFrame, you have access to all the methods of the JFrame hierarchy
  • setTitle and setBounds are methods from the hierarchy
  • The main method creates a BookOrderFrame object
  • Since a BookOrderFrame object is a JFrame, you can use a BookOrderFrame anywhere you can use a JFrame
  • In this example, we use a JFrame type to store a BookOrderFrame object reference
  • JFrame frame = new BookOrderFrame();
  • Then we call a method from the Window class to display the BookOrderFrame

7.1.5: Summary

  • You can use inheritance to create a subclass (derived, child)
  • Inherits fields and methods from a superclass (base, parent)
  • Deriving a new class from an existing one requires the extends clause
  • public class SubclassName extends SuperclassName
  • You can define new fields and methods in a subclass
  • Call constructors of the superclass using the super() method
  • super(bookCode, bookQuantity);
  • Inheritance allows you to develop hierarchies of classes
  • Subclasses can have access to fields and methods of the hierarchy

Exercise 7.1

  1. Start a text file named exercise7.txt.
  2. Prepare the exercise header as described in the HowTo on submitting exercises
  3. Label this exercise: Exercise 7.1
  4. Do not submit exercises until all from this week's lesson are finished
  5. Write one quiz-question for the information we just covered and record it in your exercise7.txt file.

7.2: Working With the Object Class

Objectives

At the end of the lesson the student will be able to:

  • Use methods of the Object class
  • Override methods of the superclasses
  • Write code to cast objects up and down inheritance chains

7.2.1: Methods of the Object Class

  • Every class implicitly extends java.lang.Object
  • This make the Object class the superclass for Java classes
    • Including all programmer-defined classes
  • Thus, every class you write has access to the fields and methods of the Object class
  • That means you need to know how to work with the Object class

Object Class Methods

  • Following is a summary of some of the methods of the Object class
  • Method Description
    clone() Returns a copy of this object as an Object object. You must implement the Cloneable interface to use this method. (Cover later)
    equals(Object obj) Returns true if this object refers to the same space in memory as another object. Otherwise, returns false even if the other object contains the same data.
    finalize() Called by the garbage collector on an object when garbage collection determines that there are no more references to the object.
    getClass() Returns a Class object that represents the class of this object.
    hashCode() Returns a hash code value for the object, which is supported for the benefit of hashtables.
    toString() Returns a String object containing the class name followed by an @ symbol and the memory location (in hexadecimal) for the object.

  • Probably the most used method is the toString method
  • Java implicitly calls this method when it needs a String representation of an object
  • System.out.println(Book);
  • When coding a class, you typically override the toString method
    • To provide more details about the object
  • Similarly, you typically override the equals method for your classes
  • One method you usually do not override is finalize
  • Java uses garbage collection to automatically manage memory
  • Method finalize is called just before an object is deleted
  • Since memory management is automatic, usually no need to override the finalize method

7.2.2: Casting Objects

  • Many methods accept and return objects of the Object class
  • For example, the equals method of Object accepts an Object argument
  • public boolean equals(Object obj)
  • Also, the clone method of Object returns an Object object
  • protected Object clone()
  • To use these methods, you need to cast objects
  • Following is the inheritance chain for BookOrder
  • Java will implicitly cast an object up the inheritance chain (upcasting)
  • Must explicitly cast an object down the inheritance chain (downcasting)
BookOrder order1 = new BookOrder("WARP", 2);
Object obj = order1;                // cast BookOrder to Object
BookOrder order2 = (BookOrder) obj; // cast Object to BookOrder
  • Following shows how casting affects the methods you can call
Object obj = new BookOrder("WARP", 2);
String orderStr = obj.toString(); // OK
// double total = obj.getTotal(); // does not compile
BookOrder order = (BookOrder)obj; // cast Object to BookOrder
double total = order.getTotal();  // OK
  • You can code your won method that accepts an Object object
  • For example:
  • public boolean equals(Object obj) {
        if (obj instanceof BookOrder) {
            BookOrder order = (BookOrder) obj;
            // ...
        }
        return false;
    }
    
  • Note use of the instanceof operator
  • Allows testing an object to determine if it is an instance of a class

7.2.3: Overriding the toString Method

  • Method toString of Object returns a String with the class name and memory location of the object
    • Not usually the behavior you want
  • Many classes in the API override this method
  • You will often want to override this method for your own classes
  • Following is an example of overriding the toString method of the Book class
  • public String toString() {
        NumberFormat currency =
                NumberFormat.getCurrencyInstance();
        return "Code: " + code
                + "\nTitle: " + title
                + "\nPrice: " + currency.format(price);
    }
    
  • With this method in place, you get a more descriptive value for a book
  • Book book = new Book("WARP");
    System.out.println(book);
    String str = "Book String: " + book;
    System.out.println(str);
    
  • Java automatically calls the toString method for println and when concatenating an object with a string

7.2.4: Overriding the equals Method

  • To test if two objects refer to the same location, use the equals method of the Object class
  • For example:
  • public class EqualsTestApp {
        public static void main(String[] args) {
            Book book1 = new Book("WARP");
            Book book2 = new Book("WARP");
            if (book1.equals(book2))
                System.out.println("true");
            else
                System.out.println("false");
        }
    }
    
  • To test if two objects store the same data, override the equals method in the subclass
  • Following example adds the necessary code
  • public boolean equals(Object obj) {
        if (obj instanceof Book) {
            Book book = (Book) obj;
            if (code.equals(book.getCode())
                    && title.equals(book.getTitle())
                    && price == book2.getPrice())
                return true;
        }
        return false;
    }
    
  • Tests whether all instance variables in two objects are equal
  • Now the EqualsTestApp will return a different value

7.2.5: Summary

  • Every class extends from Object
  • Thus you can use methods from Object in your own classes
  • You can cast an object up and down its inheritance chain
    • Will not lose any data stored in the object
  • You can also override methods of the Object class, or other superclass
  • If a method in a subclass has the same signature as a method in the superclass, the method from the subclass overrides (replaces) the superclass method
    • Will not override the superclass if the parameters are different
    • Would have a different signature
  • Overriding should not be confused with overloading (see below)
  • Object methods toString and equals are typically overridden in subclasses

Overriding Verses Overloading

Overriding Overloading
  • Same method name
  • Same method name
  • Same signature
  • One method in superclass, one in subclass
  • Different signature
  • Both methods can be in same class

Exercise 7.2

  1. Label this exercise: Exercise 7.2
  2. Complete Exercise 5-1 on page 178 of the textbook.
  3. Submit the modified .java code along with your exercise7.txt file.

Part 1 Wrap Up

Part 2: What We Will Cover

Continuations

Questions on Completed Assignment?

Questions from last class?

  • Finishing the CheckStyle install for TextPad

7.3: More About Classes

Objectives

At the end of the lesson the student will be able to:

  • Write code to throw exceptions
  • Use abstract classes
  • Use this

7.3.1: Throwing an Exception

  • In lesson 4.5.2, you learned to handle exceptions
  • Another way to deal with an exception is to throw the exception
  • Throwing an exception is like passing the buck
    • Requires the calling method to deal with the exception
  • Calling method can also pass the buck
  • Eventually some method should catch it
    • Otherwise the general exception handler is used

Checked Exceptions

  • Not all exceptions must be caught
  • However, the Java compiler checks some exceptions
  • As a result you either have to throw or catch these exceptions
  • If the compiler complains, then you need to either throw or catch an exception

How to Throw an Exception

  • General syntax for throwing an exception:
  • returnType functionName(paramterList)
            throws ExceptionType1, ExceptionType2,... {
        // method body
    }
    
  • For example:
  • public static void main(String[] args) throws IOException
    
  • Throwing from main invokes the general exception handler
  • Produces an ugly (but useful to programmers) error message

7.3.2: Abstract Classes and Methods

  • Any class can be specified with the keyword abstract
  • Indicates that objects cannot be instantiated
  • Used when classes are too generic to define real objects
  • For example: TwoDimensionalShape
  • Provides superclass from which other classes may inherit
  • Normally referred to as an abstract superclass
  • Must declare a class abstract if it contains an abstract method
  • Abstract Methods

  • Method declaration without a method body
  • void draw();
    

7.3.3: Final Classes and Methods

Final Classes

  • Use final to prevent a class from being extended
  • For example:
  • public final class String {}
  • Java's String class is declared final for reasons of security

Final Methods

  • Specifies that a method definition cannot be overridden with a new definition in a subclass
  • For example:
  • public final int getQuantity() {
        return quantity;
    }
    
  • Since you would never want the method to do anything else, it makes sense to make it final
  • Allows the compiler to generate more efficient code

Final Parameters

  • Use final in a parameter list to prevent a method from assigning a new value
  • For example:
  • public void setQuantity(final int qty) {
        quantity = qty;
    }
    
  • You almost never want to assign a parameter a new value
  • However, the final paramter does add more clutter to the code

7.3.4: Using Access Modifiers

Access Modifiers and Inheritance

  • You can put the keywords public, private and protected to control access
  • Used to control access to class instance variables and methods
  • Controls the access for only a particular definition (unlike C++)

Package Access: the Default

  • No access modifier: known as default accessibility
  • Only accessible to other classes in the same package
  • Less restrictive than private accessibility, but more restrictive than public access
  • class MyClass {
        double x;
        void foo() {}
    }
    

public Access: Interface Access

  • Least restrictive of all access modifiers
  • public fields and methods can be accessed from anywhere the class is visible
  • public class MyClass {
        public double x;
        public void foo() {}
    }
    

private Access: Don't Touch That!

  • Most restrictive of all access modifiers
  • private fields and methods cannot be accessed from outside of the class
  • Good design practice to make all variables private and to provide accessor methods where needed
  • Auxiliary ("helper") usually declared private as well
  • Cannot declare a class private -- how would you use it?
  • public class MyClass {
        private double x;
        private void foo() {}
    }
    

protected Access: Inheritance Access

  • Accessible in the package of this class and any subclass
  • More restrictive than public accessibility but less restrictive than default
  • public class MyClass {
        protected double x;
        protected void foo() {}
    }
    

7.3.5: Using the this Keyword

  • Each object maintains its own set of instance variables
  • Permits each object to have its own state based on the values stored
  • For instance, consider a class Date with 3 instance variable
  • private int month;
    private int day;
    private int year;
    
  • Distinct area of memory set aside each time an object of this class is created
  • For example, if two objects are referenced by variables named a and b
  • This replication of data storage is not implemented for methods
    • Only one copy of each member method is memory
    • Every object of that type uses these same methods
  • How can this work?
  • All methods are passed an implicit parameter named this
  • For instance, the method:
  • getMonth()
  • Is called as if it had the parameter this
  • getMonth(this)
  • this contains a reference to the object that called the method
  • Parameter this is hidden, so you do not explicitly use it in method calls
  • However, you can use the this parameter inside the class
  • Used with the dot '.' operator like any other object reference
  • this.month
  • Use of this reference is optional unless needed to clarify variable scope
  • For instance, we could define an constructor of Date:
  • public Date(int month, int day, int year) {
        this.month = month;
        this.day = day;
        this.year = year;
    }
    
  • Need this to differentiate between member variables and local variables
  • Another use is to pass this as a parameter to a method
    System.out.println(this);
  • Since this is an object reference, Java will implicitly call the toString method
  • You can also return this from a method call
  • return this;
  • Returns a reference to the current object

7.3.6: Passing Objects to Methods

  • Java passes the value stored in a variable the same way for both primitive types and reference types
  • When a method is called, value of each argument is copied to its corresponding parameter
  • Thus an argument's value can never be changed within a method
  • Passing a reference value has implications not present when passing primitive values
  • Called method gets access to the exact same object passed by the calling method
  • Situation is shown in the following diagram:

For Example

  • Following program demonstrates passing a reference value of type PassingClass
  • public class PassRef {
        public static void main(String[] args) {
            PassingClass pc = new PassingClass();
            displayMsg(pc);
            changeMsg(pc);
            System.out.println("In main: " + pc.msg);
        }
    
        public static void displayMsg(PassingClass p) {
            System.out.println("In displayMsg: " + p.msg);
        }
    
        public static void changeMsg(PassingClass p) {
            p.msg = "new message";
        }
    }
    
    class PassingClass {
        String msg = "original message";
    }
    
  • Method displayMsg accesses an instance variable of PassingClass
  • Method changeMsg modifies an instance variable of PassingClass

7.3.7: Summary

  • When coding methods, you can include a throws clause
    • "Passes the buck" by making the calling method handle the exception
  • Some exceptions are checked by the compiler
    • The compiler forces the programmer to either catch or throw the exception
  • Abstract classes provide code that you can use in subclasses
    • Can also specify abstract methods that you must implement in subclasses
  • You can use the final keyword to declare final classes
    • Cannot be extended
  • Final methods cannot be overridden by subclasses
  • Final parameters cannot be changed within methods
  • Within an object, you can use the this keyword to refer to the object
  • When Java passes an object to a class, it copies the value of the object reference
  • Because of this, the method can access and change values in the passed object

Exercise 7.3

  1. Label this exercise: Exercise 7.3
  2. Complete Exercise 5-4, steps 1-2 and 5-7 on page 179 of the textbook, including steps 5 through 8.
  3. Write one quiz-question for the information we just covered and record it in your exercise7.txt file.

Part 2 Wrap Up

Due Next:
A6: Student Records (10/29/03)
Exercise 7 (10/29/03)

Home | WebCT | Announcements | Schedule | Expectations | Syllabus
Help | FAQ's | HowTo's | Links

Last Updated: October 25 2003 @15:29:34