You are on page 1of 50

10 Reusing Code

Copyright © 2007, Oracle. All rights reserved.


Objectives

After completing this lesson, you should be able to do


the following:
• Define inheritance
• Use inheritance to define new classes
• Provide suitable constructors
• Override methods in the superclass
• Describe polymorphism
• Use polymorphism effectively
• Develop a JavaBean and incorporate it into your
application

10-2 Copyright © 2007, Oracle. All rights reserved.


Key Object-Oriented Components

• Inheritance
• Constructors referenced by subclass
• Polymorphism
• Inheritance as a fundamental in object-oriented
programming

Superclass

InventoryItem

Subclasses
Movie Game Vcr

10-3 Copyright © 2007, Oracle. All rights reserved.


10-4 Copyright © 2007, Oracle. All rights reserved.
Example of Inheritance

• The InventoryItem class defines methods and


variables.
InventoryItem

Movie

• Movie extends InventoryItem and can:


– Add new variables
– Add new methods
– Override methods in the InventoryItem class

10-5 Copyright © 2007, Oracle. All rights reserved.


10-6 Copyright © 2007, Oracle. All rights reserved.
Specifying Inheritance in Java

• Inheritance is achieved by specifying which


superclass the subclass extends.
public class InventoryItem {

}
public class Movie extends InventoryItem {

}

• Movie inherits all the variables and methods of


InventoryItem.
• If the extends keyword is missing,
java.lang.Object is the implicit superclass.

10-7 Copyright © 2007, Oracle. All rights reserved.


10-8 Copyright © 2007, Oracle. All rights reserved.
Defining Inheritance
with Oracle JDeveloper

• When creating a new class, JDeveloper asks for its


superclass:

• JDeveloper generates the code automatically.

10-9 Copyright © 2007, Oracle. All rights reserved.


Subclass and Superclass Variables

A subclass inherits all the instance variables of its


superclass.

public class InventoryItem {


Movie
private float price;
private String condition; …
price
}
condition

public class
Movie extends InventoryItem { title
private String title; length
private int length; …
}

10-10 Copyright © 2007, Oracle. All rights reserved.


Default Initialization

• What happens when a subclass


object is created?

Movie movie1 = new Movie(); Movie

• If no constructors are defined: price


condition
– The default no-arg constructor
is called in the superclass.
– The default no-arg constructor title
is then called in the subclass. length

10-11 Copyright © 2007, Oracle. All rights reserved.


Super() Reference

• Refers to the base superclass


• Is useful for calling base class constructors
• Must be the first line in the derived class
constructor

10-12 Copyright © 2007, Oracle. All rights reserved.


Super() Reference: Example

public class InventoryItem {


Base class
InventoryItem(String cond) { constructor
System.out.println("InventoryItem");

}
}
public class Movie extends InventoryItem {
Movie(String t, float p, String cond) { Calls
base class
super(cond); constructor

System.out.println("Movie");
}
}

10-13 Copyright © 2007, Oracle. All rights reserved.


Using Superclass Constructors

Use super() to call a superclass constructor:

public class InventoryItem {


InventoryItem(float p, String cond) {
price = p;
condition = cond;
} …
public class Movie extends InventoryItem {
Movie(String t, float p, String cond) {
super(p, cond);
title = t;
} …

10-14 Copyright © 2007, Oracle. All rights reserved.


10-15 Copyright © 2007, Oracle. All rights reserved.
Specifying Additional Methods

• The superclass defines methods for all types of


InventoryItem.
• The subclass can specify additional methods that
are specific to Movie.

public class InventoryItem {


public float calcDeposit()…
public String calcDateDue()…
… public class Movie extends InventoryItem {
public void getTitle()…
public String getLength()…

10-16 Copyright © 2007, Oracle. All rights reserved.


10-17 Copyright © 2007, Oracle. All rights reserved.
Overriding Superclass Methods

• A subclass inherits all the methods of its


superclass.
• The subclass can override a method with its own
specialized version.
– The subclass method must have the same signature
and semantics as the superclass method.

public class InventoryItem {


public float calcDeposit(int custId) {
if … public class Vcr extends InventoryItem {
return itemDeposit;
public float calcDeposit(int custId) {
} if …
return itemDeposit;
}

10-18 Copyright © 2007, Oracle. All rights reserved.


10-19 Copyright © 2007, Oracle. All rights reserved.
Invoking Superclass Methods

• If a subclass overrides a method, it can still call


the original superclass method.
• Use super.method() to call a superclass method
from the subclass.

public class InventoryItem {


public float calcDeposit(int custId) {
if …public class Vcr extends InventoryItem {
return 33.00;
public float calcDeposit(int custId) {
} itemDeposit = super.calcDeposit(custId);
return (itemDeposit + vcrDeposit);
}

10-20 Copyright © 2007, Oracle. All rights reserved.


Example of Polymorphism in Java

Recall that the java.lang.Object class is the root


class for all Java classes.
• Methods in the Object class are inherited by its
subclasses.
• The toString()method is most commonly
overridden to achieve polymorphic behavior.
• Example: public class InventoryItem {
public String toString() {
return "InventoryItem value";
}
} = new InventoryItem();
InventoryItem item
System.out.println(item); // toString() called

10-21 Copyright © 2007, Oracle. All rights reserved.


Treating a Subclass As Its Superclass

A Java object instance of a subclass is assignable to


its superclass definition.
• You can assign a subclass object to a reference
that is declared with the superclass.
public static void main(String[] args) {
InventoryItem item = new Vcr();
double deposit = item.calcDeposit();
}

• The compiler treats the object via its reference


(that is, in terms of its superclass definition).
• The JVM run-time environment creates a subclass
object, executing subclass methods, if overridden.
10-22 Copyright © 2007, Oracle. All rights reserved.
10-23 Copyright © 2007, Oracle. All rights reserved.
Browsing Superclass References
with Oracle JDeveloper

Oracle JDeveloper makes it


easy to browse the contents
1
of your superclass.

2 3

10-24 Copyright © 2007, Oracle. All rights reserved.


Hierarchy Browser
• Select the class
and choose View
Type Hierarchy
from the shortcut
menu.

• The Hierarchy
window displays the
class hierarchy.

10-25 Copyright © 2007, Oracle. All rights reserved.


Acme Video and Polymorphism

• Acme Video started renting only videos.


• Acme Video added games and VCRs.
• What is next?
• Polymorphism solves the problem.

10-26 Copyright © 2007, Oracle. All rights reserved.


Using Polymorphism for Acme Video

InventoryItem
calcDeposit(){…}

Vcr Movie
calcDeposit(){…} calcDeposit(){…}

ShoppingBasket
void addItem(InventoryItem item) {
// this method is called each time
// the clerk scans in a new item
float deposit = item.calcDeposit();

}

10-27 Copyright © 2007, Oracle. All rights reserved.


10-28 Copyright © 2007, Oracle. All rights reserved.
instanceof Operator

• You can determine the true type of an object by


using an instanceof operator.
• An object reference can be downcast to the
correct type if necessary.

public void aMethod(InventoryItem i) {



if (i instanceof Vcr)
((Vcr)i).playTestTape();
}

10-29 Copyright © 2007, Oracle. All rights reserved.


10-30 Copyright © 2007, Oracle. All rights reserved.
Limiting Methods and Classes with final

• You can mark a method as final to prevent it


from being overridden.
public final boolean checkPassword(String p) {

}

• You can mark a whole class as final to prevent it


from being extended.
public final class Color {

}

10-31 Copyright © 2007, Oracle. All rights reserved.


10-32 Copyright © 2007, Oracle. All rights reserved.
Ensuring Genuine Inheritance

• Inheritance must be used only for genuine “is a


kind of” relationships:
– It must always be possible to substitute a subclass
object for a superclass object.
– All methods in the superclass must make sense in
the subclass.
• Inheritance for short-term convenience leads to
problems in the future.

10-33 Copyright © 2007, Oracle. All rights reserved.


Practice 10 Overview: Reusing Code
with Inheritance and Polymorphism

This practice covers the following topics:


• Defining subclasses of Customer
• Providing subclass constructors
• Adding new methods in the subclasses
• Overriding existing superclass methods

10-34 Copyright © 2007, Oracle. All rights reserved.


10-35 Copyright © 2007, Oracle. All rights reserved.
10-36 Copyright © 2007, Oracle. All rights reserved.
10-37 Copyright © 2007, Oracle. All rights reserved.
10-38 Copyright © 2007, Oracle. All rights reserved.
10-39 Copyright © 2007, Oracle. All rights reserved.
10-40 Copyright © 2007, Oracle. All rights reserved.
JavaBeans
JavaBeans are platform-neutral reusable software
components that:
• Have a public class declaration and a no-arg
constructor
• Can be easily assembled to create sophisticated
applications
• Can be manipulated visually in a builder tool
• Can exist on either the client or the server side
• Provide an architecture for constructing the
building blocks of an application
• Perform a distinct task

10-41 Copyright © 2007, Oracle. All rights reserved.


More About JavaBeans

JavaBeans contain:
• Properties that can be exposed
• Private data with accessor and mutator methods
• Events they can fire or handle
JavaBeans support:
• Introspection and reflection
• Customization
• Persistence

10-42 Copyright © 2007, Oracle. All rights reserved.


Managing Bean Properties

• Properties are accessed via method calls on their


owning object.
• Properties can be simple data fields or computed
values.
• A property can be:
– Unbound: A simple property
– Bound: Triggers an event when the field is altered
– Constrained: Changes are accepted or vetoed by
interested listener objects.

10-43 Copyright © 2007, Oracle. All rights reserved.


Exposing Properties and Methods

Getter Setter
private
methods T var; methods
(public) T[] arr; (public void)

T getVar() setVar(T val)

T[] getArr() setArr(T[] val)

boolean isVar() setVar(boolean val)

10-44 Copyright © 2007, Oracle. All rights reserved.


JavaBeans at Design Time

The benefits at design time include:


• A facilitated interaction among designer, tool, and
bean
• Instantiated and functioning beans in a visual tool
• Highly iterative development environment
• Building applications in small bits that plug in and
out
• Storage and recovery of instantiated
objects

10-45 Copyright © 2007, Oracle. All rights reserved.


Introspection with JavaBeans

• Introspection is a mechanism that is used by a


visual tool to determine the properties, methods,
and events that a bean supports.
• The tool examines a bean to discover its
properties and events.
• Information is displayed in the Property Inspector
window.
JDeveloper

10-46 Copyright © 2007, Oracle. All rights reserved.


JavaBeans at Run Time

• Always run in a single JVM


• Support multithreaded access
• Can use locale-dependent controls

10-47 Copyright © 2007, Oracle. All rights reserved.


Build and Use a JavaBean
in JDeveloper

1. Develop a JavaBean.
– Modified via code, class, or UI editors
2. Store the bean in an archive file.
3. Create a JDeveloper library identifying the archive.
4. Install the bean in the JDeveloper Component
Palette via its library name.
5. Develop an application that uses the JavaBean
component.

10-48 Copyright © 2007, Oracle. All rights reserved.


Summary

In this lesson, you should have learned the following:


• Inheritance and polymorphism are object-oriented
programming techniques that involve the reuse of
existing code.
• A subclass inherits all the variables and methods
of its superclass.
• You can specify additional variables and methods
and override methods.
• A subclass can call an overridden superclass
method by using super.
• Polymorphism ensures that the correct version of
a generic method is called at run time.
• JavaBeans are reusable software components that
you can manipulate with JDeveloper.

10-49 Copyright © 2007, Oracle. All rights reserved.


10-50 Copyright © 2007, Oracle. All rights reserved.