Title: Reference Objects First with Java 3rd edition David j' Barnes Micheal Kolling ch10 Lecture outline A
1ReferenceObjects First with Java3rd
editionDavid j. BarnesMicheal
Kollingch10Lecture outline Abstract Classes
Interfaces
2Abstract Classes
- Abstract classes starting points for deriving
trees of subclasses (starting point for creating
subclasses) - Bottom up design
- 1. identify which classes well need
- 2. factor out what they have in common
(refactoring) - Result is an abstract class that we can extend to
create the classes that were really interested
in
3Animal Abstract class
Bottom up design 1. identify which classes
well need 2. factor out what they have in
common (refactoring) Result is an abstract class
that we can extend to create the classes that
were really interested in
- E.g rabbit, foxes all have some similar
characteristics should be subclasses of a common
superclass Animal - Identical elements of rabbit foxes can be moved
to an Animal superclass - Age, alive, location
-
- Public Abstract class Animal
- ..
-
Animal
rabbit
Fox
4Coupling
- But moving these to Animal raises question what
visibility they should have - IncrementAge method needs to be able to get and
set the value of age. One possibility is to
declare these fields as Protected - But this creates strong coupling between these
classes loser coupling can be achieved by
declaring the fields as private and providing
accessor and mutator methods. - The subclasses can then use these to inspect and
manipulate the attributes
5Access modifiers in Java
6Abstract classes
- Creating a superclass Animal (abstract class)
- We never have an instance of Animal class
- So what are the benefits?
- Helps to avoid code duplication in in rabbits and
foxes classes - Makes it easier to add new classes in future
- Intelligent use of inheritance simplifies client
class
Animal
rabbit
Fox
cat
7Abstract Methods
- Although we know each item is an Animal
- We still have to work out which type of Animal it
is in order to call the correct action method - Use instanceof
- Test if object is an instance of class
8- Each type of animal must be tested for and cast
separately - special code exists for each animal
- We not taken full advantage of inheritance
- Instead
- Have a method animal act at abstract class level
-
- And redefine this method in EACH subclass level
- So rabbit will Overide
- act method according to itself
- Can use a polymorphic method call to let each
animal act, avoids testing for specific animal
types
- If (animal instanceof Rabbit)
- Rabbit rabbit (Rabbit) animal
- rabbit.run(updatedField, newAnimals)
-
- elseif (animal instanceof Fox)
- Fox fox (fox) animal
- fox.hunt(field, updatedField, newAnimals)
9 Abstract Methods
- Animal.act(field, updatedField,newAnimals)
- (Have a method animal act
at abstract class level) - Specific methods (run for Rabbit and, hunt for
Fox) have been renamed act - So instead of telling each animal exactly what to
do we just telling it to act we leave it to
the animal itself to decide what it wants to do - But run method for Rabbit had only two
parameters updatedField and newRabbit. We added
a third parameter field to make it consistent
with foxs act method - Now all animals get all parameters possibly
needed to implement flexible action each class
chooses or ignores any of the parameters! - Animal has to have act method with right
signature - public abstract class Animal
-
- Abstract public void act(Field currentField,
- Field updatedField,
- Animal newAnimals)
Animal Abstract class Abstract method - act
rabbit
Fox Overide act method
10Abstract Methods Polymorphism and Overiding
- Not about inheritance because we not inheriting
any concrete methods from Abstract class they
are Abstract so just empty method body - But Allows us to overide the abstract methods
and make it specific for our subclasses - We can use polymorphism declare type and call
appropriate method - Remember the vehicle abstract class
- EXAMPLE Vehicle
- Start
- Release brake
- Accelerate
- Apply brake
- Stop
- Vehicle v1 new Car()
- V1.start() // Calls start method in Car class
- Vehicle v2 new Truck()
Vehicle Abstract class Abstract method start,
release..
Truck
car Overide start method
11Abstract Methods
- No instance of Animal class will ever exist - No
animal object - Abstract class serves as a superclass for
subclasses - Animal can act but we cannot describe how it
acts the specific classes will specify that - So at the abstract class level we define an
abstract method
12Abstract Methods
- Prefixed with keyword abstract
- It does NOT have a method body, instead its
header is terminated by a semicolon. - Since method has no body it can never be executed
- But thats no problem we dont want to execute an
Animals act method - The subclasses will overide this method
accordingly
13Declaring a class abstract can have the following
benefits
- We dont want instances of Animal class class
serves only as a superclass declaring as
abstract enforces this - Only abstract classes can have abstract methods.
- This ensures all methods in concrete classes can
always be executed. - Abstract classes with abstract methods force
subclasses to overide and implement those methods
declared as abstract - For subclass to be concrete it must provide
implementations of ALL inherited abstract methods
Animal Abstract class Abstract method - act
rabbit
Fox Overide act method
14Declaring a class abstract can have the following
benefits
- Purpose of abstract methods although they do
not provide an implementation they force
subclasses to provide implementation of this
method - Thus even though Animal does not implement the
act method, it ensures that all existing animals
have an implemented act method. - This is done by -
- No instance of Animal class can be created
directly and - All concrete subclasses must implement the act
method
15 16Interfaces
- Similar to abstract methods all methods are
abstract - So what is the difference?
17Interfaces significant features
- Keyword interfaces used
- As all methods in interfaces are abstract and no
method bodies are permitted (no need for
abstract keyword). - All method signatures in interface have public
visibility (no need for keyword public for
each method) - No fields , no constructors, no method bodies
- Class can inherit from a interface in same way it
inherits from class - Class implements an interface
- public class Fox extends Animal implements Food
- .
-
- Class both extends a class and implements an
interface, note - extend clause is written first
18Whereas .
- Abstract classes can contain partial
implementation - (many methods have method bodies) and only one
single abstract method
19List
ltltinterfacegtgt List
implements
implements
ArrayList
LinkedList
void addFirst(o obj)void addLast(o obj)
getFirst() getLast() removeFirst() removeLast()
20Java collections interface example
- Collection hierarchy there is a List
implementation - An interface does not give any implementation
- The List interface specifies the full
functionality of a list an interface defines a
contract for a set of operations a given
operation in one class maybe implemented
differently from how it is implemented in another
class. But the way in which you invoke the
operation is the same for objects of all class
types that implement the interface - The subclasses ArrayList and LinkedList provide
two different implementations of same interface - The two implementations differ greatly in
efficiency of their functions - ArrayList faster for random access to elements in
middle of the list - Insertions and deletions of elements faster in
LinkedList - List interface makes it easy to swap between the
two implementations simply plug in and out
just change ArrayList to LinkedList - Private ListltTypegt myList new ArrayListltTypegt
-
21Multiple Inheritance of interfaces
- Java allows any class to extend at most one other
class - Java allows a class to implement any number of
interfaces - Public interface MyInterface extends
HisInterface,HerInterface - abstract methods
Interface 3
Interface 1
Interface 2
class
The class inherits the method definition of all
interfaces as abstract methods, It must then
provide method definitions for all of them by
overriding the methods
class
subclass
subclass
22Important use of Interfaces
- When a class implements an interface, it does not
inherit any implementation from it, as they dont
contain method bodies - So what benefits?
- interfaces benefit is that allows for multiple
inheritance in Java.
23Abstract or Interface ?
- If the class needs to contain some implementation
for some methods use an abstract classes - If we have a choice interfaces are preferable,
- If its an abstract class subclasses cannot
extend any other classes, - Interfaces allow for multiple inheritance
- Thus interfaces allow for a more flexible and
extendable structure
24- Bottom up design
- 1. identify which classes well need
- 2. factor out what they have in common
(refactoring)
Parent class
All common Generalisation specialisation
Abstract classes
Sub class
Sub class
Dummy class Dummy abstract methods must be
overide by subclasses Can have concrete methods
which will be inherited by child
Visibility Inheritance
Interface 3
Interface 1
Interface 2
- Interfaces provide a contract what
functionality should we have - have only abstract methods no concrete ones
- Allows for multiple inheritance
class