Download Chapter 2: Using Objects

Document related concepts
no text concepts found
Transcript
Inheritance

Another fundamental object-oriented technique is called
inheritance, 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
1
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.
2
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.
3
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.
4
Inheritance

As the name implies, the child inherits characteristics of the
parent.

That is, the child class inherits the methods and data
defined for the parent class

This means that you can write the code for one class
and have all its child classes have access to it.
5
Inheritance

Inheritance relationships are shown in a UML class
diagram using a solid arrow with an unfilled triangular
arrowhead pointing to the parent class
Vehicle
Car

Proper inheritance creates an is-a relationship, meaning
the child is a more specific version of the parent
6
Inheritance

A subclass inherits state and behavior.

Recall that an object’s state is reflected in the form of instance
variables and its behavior in the form of methods.

The child inherits both from all of its ancestors.
7
Inheritance

Child classes can use the items inherited from its parent or
super class as is, or the child class can modify or override
the methods of the parent class.

This means that the child class can contain a method with
the same name as the parent class.
8
Inheritance

A programmer can tailor a derived class as needed by
adding new variables or methods, or by modifying the
inherited ones

Software reuse is a fundamental benefit of inheritance

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
9
Child Classes

The method in the child class deals with the behavior
that is particular to the child class.

We have a class SHAPE and SHAPE has a child class
RECTANGLE and a child class TRIANGLE.

The SHAPE class will contain methods that are
common to both child classes, e.g. and Area() method

Both child classes will have a method that calculates its
Area.

Only the formulas for each Area calculation will differ.
10
Inheritance

This leads to smaller and easier to understand systems.

Using inheritance, common descriptions can be reused,
promoting the concept of code reusability.

A child class can have a method with the same name as
the parent class only its method implements what it is
capable of doing.
11
Inheritance

Inheritance cuts redundancy as descendant classes only
implement the extra information that differentiates them
from the parent class

When changes are made on the common information, all
child classes automatically inherit it.

Thus the models that are created are easier to modify and
implement.

In Java, the reserved word extends is used to establish an
inheritance relationship
12
Sub or Child Classes

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.

Member variables defined in the subclass hide member
variables of the same name in the superclass. Consider
this superclass and subclass pair:
13
Sub or Child Classes
class Super {
protected int num;
public Super(int anum){
num = anum;
}
class Sub extends Super {
float num1;
public Sub(int newnum, float Fnum) {
super(newnum)
num1 = Fnum;
}
14
Deriving Subclasses

In Java, we use the reserved word extends to establish an
inheritance relationship
class Car extends Vehicle
{
// class contents
}



See Words.java
See Book.java
See Dictionary.java
15
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

But public variables violate our goal of encapsulation

There is a third visibility modifier that helps in inheritance
situations: protected
16
The protected Modifier

The protected visibility modifier allows a member of a
base class to be inherited into the child

The protected visibility modifier provides more
encapsulation than public does.

Encapsulation requires that we protect as much as possible
out instance variables from outside accesss.

The details of each modifier are given in Appendix F
17
The protected Modifier

The 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.

But public variables violate our goal of encapsulation.

The protected visibility modifier allows a member to
be inherited, but provides more protection than public
does.
18
The super Reference

Constructors are not inherited, even though they have
public visibility

Yet we often want to use the parent's constructor to set up
the "parent's part" of the object

The super reference can be used to refer to the parent
class, and is often used to invoke the parent's constructor

See Words2.java (page 328)
See Book2.java (page 329)
See Dictionary2.java (page 330)


19
Class Diagram for Words
Book
# pages : int
+ pageMessage() : void
Words
Dictionary
- definitions : int
+ main (args : String[]) : void
+ definitionMessage() : void
20
The Super Reference

The super reference can be used to refer to the parent
class, and is often used to invoke the parent's constructor.

In Words2.java, The Dictionary class uses the super
reference to call the parent constructor so that the number
of pages can be set.

If it did not call the parent constructor, it would have to
initialize the number of pages in its own constructor. Let us
look at Words2.java
21
Super Reference

When we create the constructor for a child class, we should
invoke the constructor for the superclass also.

To do this, the first line of our constructor should contain
the keyword super followed by a parameter list as though
calling a method named super().

The parameter list must match the parameters in the
argument list of the superclass constructor.e.g.
super(num_pages) // initializes the # of pages
22
Super Reference

This causes the constructor for the superclass to be invoked
using parameters passed from the subclass.

Thus memory is allocated for all the data in the super class.
The child class now has full access to it.
23
Inheritance

The Dictionary class invokes the parent class constructor
with:
super(num_pages)

Since the Dictionary class inherits the variable pages from
the parent class Book, it has to initialize this variable in its
constructor.

But the parent class constructor already does this
initialization.

Since constructors are not inherited, the Dictionary sub
class can use the super reference to invoke the parent class
constructor.
24
The Super Reference

A child object inherits the allowable fields and methods of
its parent . The one duty of the default constructor is to
support this.

Each instance of a child class inherits the specified
methods and variables of the parent class. So the parent
class’s instance variables must be properly initialized.
25
Inheritance and Constructors

Every constructor has 3 tasks to perform:
1. Instantiate the parent object and initialize its
fields
2. Initialize any fields local to its class
3. perform the statements in the constructor

If you do not call the parent constructor with super
when the super class constructor has parameters, then
the instance variables in the parent class will not be
initialized.
26
Defined vs. Inherited

A subtle feature of inheritance is the fact that even if a
method or variable is not inherited by a child, it is still
defined for that child.

An inherited member can be referenced directly in the child
class, as if it were declared in the child class

But even members that are not inherited exist for the child,
and can be referenced indirectly through parent methods

In Eating.Java, a pizza object is created that can access
private methods and variables in the parent class.
27
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.

That is, a child can redefine a method it inherits from its
parent.

The new method must have the same signature as the
parent's method, but can have different code in the body
28
Overriding Methods




See Messages.java
See Thought.java
See Advice.java
Note that a parent method can be explicitly invoked using
the super reference
29
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

Overloading lets you define a similar operation in different
ways for different data

Overriding lets you define a similar operation in different
ways for different object types
30
Overriding Methods

A subclass can either completely override an inherited
method, or the subclass can enhance it.

The subclass can use the keyword super to invoke the
version in the superclass.

For instance, if have a method called deposit() in the child
class and a method called deposit() in the parent class, the
child class would call the parent method with:
super.deposit(45.00)
31
OverRiding

The object type determines which method is invoked.
Savings_Account s = new Savings_Account(“Tom”);
Account b = new Account(“Bob”);
s.deposit(25.00); // defined in Savings_Account
b.deposit(25.00); // method defined in Account class

Don't confuse the concepts of overloading and overriding
32
Overriding Methods

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.

If you aren't careful when writing your new method
signature, you will be overloading methods when you think
that you are overriding them.

This is a situation where you don't get any warnings from
the JDK compiler.
33
Overriding

If a method is declared with the final modifier, it cannot
be overridden

The concept of overriding can be applied to data and is
called shadowing variables

Shadowing variables should be avoided because it tends to
cause unnecessarily confusing code
34
The super Reference Revisited

A method in the parent class can be invoked explicitly using
the super reference

The super reference can be used to invoke any method
from the parent class.

This ability is often helpful when using overridden methods

The syntax is:
super.method(parameters)
See Accounts.java
35
SubClasses

When we extend an existing class, we 'inherit' all of the
attributes, and methods, of the parent class.

In the Accounts.java program, the child class can deposit,
and withdraw - even though we only explicitly define a
new method for withdrawal.

This makes programming much easier, and simpler, as we
don't re-invent the wheel each time we extend other
classes.

In the example above, we add two new methods , and call
the constructor of our parent class.
36
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 reasonable.

Class hierarchies often have to be extended and modified
to keep up with changing needs

There is no single class hierarchy that is appropriate for
all situations
37
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

Collisions, such as the same variable name in two parents, have
to be resolved

In most cases, the use of interfaces gives us the best aspects of
multiple inheritance without the overhead
38
Class Hierarchies

A child class of one parent can be the parent of another
child, forming class hierarchies
Business
RetailBusiness
KMart
Macys
ServiceBusiness
Penny’s
39
The Object Class

A class called Object is defined in the java.lang
package of the Java standard class library

All classes are derived from the Object class

If a class is not explicitly defined to be the child of an
existing class, it is assumed to be the child of the Object
class

The Object class is therefore the ultimate root of all class
hierarchies
40
The Object Class

The Object class contains a few useful methods, which are
inherited by all classes

For example, the toString method is defined in the
Object class

Every time we have defined toString, we have actually
been overriding it

The toString method in the Object class is defined to
return a string that contains the name of the object’s class
and a hash value
41
Class Object

The class Object defines the following methods:
•
•
•
•
•
•
•
•
•
•
•

clone()
equals(Object obj)
finalize()
getClass()
hashCode()
notify()
notifyAll()
toString()
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).
42
Class Object

Because every class is either a direct or indirect subclass of
Object, every class in Java, (including new classes that you
define), inherit these eleven methods.

Generally speaking, 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.
43
The Object Class

That’s why the println method can call toString for
any object that is passed to it – all objects are guaranteed to
have a toString method via inheritance

See Academia.java
See Student.java
See GradStudent.java


The equals method of the Object class determines if two
references are aliases

You may choose to override equals to define equality in
some other way
44
References and Inheritance

Assigning a predecessor object to an ancestor reference is
considered to be a widening conversion, and can be
performed by simple assignment

Assigning an ancestor object to a predecessor 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
45
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.
46
Polymorphism


In some cases, multiple methods have the same name, but
different formal argument lists (overloaded methods).
•
In other cases, multiple methods have the same name, same
return type, and same formal argument list (overridden
methods).
Three distinct forms of polymorphism
 Method overloading
 Method overriding through inheritance
 Method overriding through the Java interface
47
Polymorphism via Inheritance

A polymorphic reference is one which can refer to different
types of objects at different times.

Inheritance can also 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
48
Polymorphism via Inheritance

Suppose the Holiday class has a method called
celebrate, and the Christmas class overrode it

Now consider the following invocation:
day.celebrate();

If day refers to a Holiday object, it invokes the Holiday
version of celebrate; if it refers to a Christmas object,
it invokes the Christmas version
49
Inheritance
Accounts[] customer= new Accounts[10];
Senior_Savings Sam = new Senior_Savings(“Sam”);
customer[5] = Sam;
Accounts Ricky = new Accounts(“Ricky”);
customer[3] = Ricky;
So the array customer of class Accounts holds both SeniorSavings and regular Accounts.
50
Polymorphism

The Senior_Savings class overrides the Account class
method deposit with a deposit method of its own.

We assign a position in the customer accounts array
(which is an array of Customer accounts) to a
Senior_Savings account.

So the customer holds both regular customer accounts
and Senior_Savings accounts.

The deposit method that is called depends on what type
of object is in the array.
51
Class Bank
public class Bank
{
public static void main(String args[]) {
Account [] customer = new Account[10];
for (int i=0; i< 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();
acctype = type.charAt(0);
if(acctype == 'S'){
customer[i] = new Senior_Savings(Name, acctype, accountnumber++);
}
else if (acctype == 'R’)
customer[i] = new Account(Name, acctype, accountnumber++);
} // close for
52
Class Account

When we call the deposit method in a loop , the deposit
method that is called depends on whether the object in the
array is of the Account class or the Senior_Savings class.
if(acctype == 'S')
{
customer[i] = new SeniorSavings(name, acctype, accnum++);
customer[i].deposit(45);
}
else if (acctype == 'R’)
{
customer [i] = new Account(name, acctype, acctnum++);
customer[i].deposit(75);
}
53
Polymorphism

In general, it is the type of the object being referenced
determines which method is invoked.


Objects of Thought class and Advice class are
instantiated. They both contain a method called message.

Initially, they each call their respective methods. Then the
Thought object is assigned the value of the advice object.
54
Polymorphism

When the message method is invoked by the Thought object,
the advice version is executed.

Note that, if an invocation is in a loop, the exact same line of
code could execute different methods at different times.

Polymorphic references are therefore resolved at run-time, not
during compilation
55
Polymorphism

Note that, because all classes inherit from the Object
class, an Object reference can refer to any type of
object .

A ArrayList is designed to store Object references of
any type.

The instanceOf operator can be used to determine
the class from which an object was created
56
Variety. java
public static void main (String[] args) {
// create a vector called collector
ArrayList collector = new ArrayLIst();
// create an integer object num1
Integer num1 = new Integer (10);
collector.add(num1);
// create an point object, origin
Point origin = new Point (0, 0);
collector.add(origin);
// create an integer object and store it in the vector
Integer num2 = new Integer (37);
collector.add (num2);
57
Variety Program

int temp;
Object someObject;
for (int count=0; count < 4; count++) {
someObject = collector.elementAt (count);
if (someObject instanceof Integer) {
temp = ((Integer)someObject).intValue() + 20;
System.out.println (something + " + 20 = " + temp);
} else
System.out.println ("Point: " + something);
}
} // method main
58
Variety.java

In the Variety program, while iterating through a loop different
objects as assigned to an object which is defined as;
someObject = collector.elementAt(count);
if (someObject.instanceof Integer){


Polymorphism means that the sender of a message does not
need to to be aware of which class the receiving object belongs
to.
The receiving instance can belong to an any class
59
Polymorphism

A sender object needs only to know that another object
can perform a certain behavior, not which class it
belongs to nor which operations will perform that
behavior.

Flexible systems can thus be implemented.

When a new object from a new class is added, this
modification should only affect this new object not those
who send messages to it
60
Indirect Access

An inherited member can be referenced directly by name in
the child class, as if it were declared in the child class

But even if a method or variable is not inherited by a child,
it can still be accessed indirectly through parent methods

See FoodAnalysis.java (page 355)
See FoodItem.java (page 356)
See Pizza.java (page 357)


61
Final Methods
A final method cannot be overridden.
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.
final classes cannot be extended.
62
Abstract Classes

An abstract class is a placeholder in a class hierarchy that
represents a generic concept

An abstract class cannot be instantiated

We use the modifier abstract on the class header to
declare a class as abstract

An abstract class often contains abstract methods (like an
interface does), though it doesn’t have to
63
Abstract Classes

An abstract class is a placeholder in a class hierarchy that
represents a generic concept

An abstract class cannot be instantiated

We use the modifier abstract on the class header to
declare a class as abstract:
public abstract class Product
{
// contents
}
64
Abstract Classes

An abstract class often contains abstract methods with
no definitions (like an interface)

Unlike an interface, the abstract modifier must be
applied to each abstract method

Also, an abstract class typically contains non-abstract
methods with full definitions

A class declared as abstract does not have to contain
abstract methods -- simply declaring it as abstract makes
it so
65
Abstract Classes

The child of an abstract class must override the abstract
methods of the parent, or it too will be considered abstract

An abstract method cannot be defined as final or
static

The use of abstract classes is an important element of
software design – it allows us to establish common elements
in a hierarchy that are too generic to instantiate
66
Interface Hierarchies

Inheritance can be applied to interfaces as well as classes

That is, one interface can be derived from another
interface

The child interface inherits all abstract methods of the
parent

A class implementing the child interface must define all
methods from both the ancestor and child interfaces

Note that class hierarchies and interface hierarchies are
distinct (they do not overlap)
67
Abstract Classes

The child of an abstract class must override the abstract
methods of the parent, or it too will be considered abstract

An abstract method cannot be defined as final (because it
must be overridden) or static (because it has no definition
yet)

The use of abstract classes is a design decision; it helps us
establish common elements in a class that is to general to
instantiate
68
Applets and Inheritance

An applet is an excellent example of inheritance

Recall that when we define an applet, we extend the
Applet class

The Applet class already handles all the details about
applet creation and execution, including the interaction
with a web browser

Our applet classes only have to deal with issues that
specifically relate to what our particular applet will do
69
Extending Event Adapter Classes

The creation of listener classes is done by implementing a
particular interface (such as MouseListener interface)

A listener can also be created by extending a special adapter
class of the Java class library

Each listener interface has a corresponding adapter class
(such as the MouseAdapter class)

Each adapter class implements the corresponding listener
and provides empty method definitions
70
Extending Event Adapter Classes

When you derive a listener class from an adapter class, you
override any event methods of interest (such as the
mouseClicked method)

Note that this avoids the need to create empty definitions
for unused events

See OffCenter.java (page 360)
71
GUI Components

A GUI component is an object that represents a visual entity
in an graphical user interface (such as a button or slider)

Components can generate events to which listener objects
can respond

For example, an applet is a component that can generate
mouse events

An applet is also a special kind of component, called a
container, in which other components can be placed
72
GUI Components

See Fahrenheit.java (page 363)

Components are organized into an inheritance class
hierarchy so that they can easily share characteristics

When we define certain methods, such as the paint
method of an applet, we are actually overriding a method
defined in the Component class, which is ultimately
inherited into the Applet class

See Doodle.java (page 367)
See DoodleCanvas.java (page 369)

73