Download presentation
1
Further abstraction techniques
Abstract classes and interfaces 5.0
2
Main concepts to be covered
Objects First with Java Main concepts to be covered Abstract classes Interfaces Multiple inheritance Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling © David J. Barnes and Michael Kölling 2
3
Simulations Programs regularly used to simulate real-world activities
city traffic the weather nuclear processes stock market fluctuations environmental changes Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
4
Simulations They are often only partial simulations
They often involve simplifications Greater detail has the potential to provide greater accuracy Greater detail typically requires more resource Processing power Simulation time Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
5
Benefits of simulations
Support useful prediction The weather Allow experimentation Safer, cheaper, quicker Example: ‘How will the wildlife be affected if we cut a highway through the middle of this national park?’ Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
6
Predator-prey simulations
There is often a delicate balance between species A lot of prey means a lot of food A lot of food encourages higher predator numbers More predators eat more prey Less prey means less food Less food means ... Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
7
The foxes-and-rabbits project
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
8
Main classes of interest
Fox Simple model of a type of predator Rabbit Simple model of a type of prey Simulator Manages the overall simulation task Holds a collection of foxes and rabbits Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
9
The remaining classes Field Location
Represents a 2D field composed of a fixed number of locations in rows/columns Only 1 animal may occupy a single location Location Represents a 2D position specified by a row and column value SimulatorView, FieldStats, Counter Provides a graphical display of the field Maintains current statistics of simulation Randomizer Produces randomization with a degree of control
10
Example of SimulatorView
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
11
A Rabbit’s state public class Rabbit {
Static fields defining config settings omitted. // Individual characteristics (instance fields) // The rabbit's age (# defined in simulation steps) private int age; // Whether the rabbit is alive or not. private boolean alive; // The rabbit's position private Location location; // The field occupied private Field field; Methods omitted. } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
12
Managed from the run method
A Rabbit’s behavior Managed from the run method age incremented at each simulation step A rabbit could die at this point (not alive) If old enough, might also breed at a step New rabbits could be born at this point Tries to move from current position (run) May change location to a free adjacent position only If no open adjacent locations, it dies Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
13
Rabbit simplifications
Rabbits do not have different genders In effect, all are female and may breed Does this affect the simulation? Same rabbit could breed at every step All rabbits die at the same age What other simplifications are there? Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
14
A Fox’s state public class Fox {
{ Static fields defining config settings omitted // The fox's age private int age; // Whether the fox is alive or not private boolean alive; // The fox's position private Location location; // The field occupied private Field field; // The fox's food level (# steps it can go before // eating again) is increased by eating rabbits private int foodLevel; Methods omitted. } Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
15
Managed from the hunt method
A Fox’s behavior Managed from the hunt method Foxes age and breed similar to rabbits A fox could die if too old (not alive) New foxes could be also born Foxes now can become hungry A fox could die at this point too Tries to move to hunt and find food Change location to adjacent position with a rabbit to kill and increase its food level If no open adjacent locations at all, it also is overcrowded and dies
16
Configuration of foxes
Similar simplifications to rabbits Hunting and eating could be modeled in many different ways Should food level be additive? Is a hungry fox more or less likely to hunt? Are simplifications ever acceptable? Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
17
The Simulator class Three key components: Setup in the constructor
fields, animal lists and graphical interface The populate method Randomly populate each location (row, column) in the field with an animal or nothing at all Each animal is also given a random starting age to reflect the true nature of an environment The simulateOneStep method Iterates over entire rabbits & foxes populations rabbits will run (and possibly breed or die) foxes will hunt (and possibly breed, find food or die)
18
The update step Very similar code!!
for(Iterator<Rabbit> it = rabbits.iterator(); it.hasNext(); ) { Rabbit rabbit = it.next(); rabbit.run(newRabbits); if(! rabbit.isAlive()) { it.remove(); } … for(Iterator<Fox> it = foxes.iterator(); Fox fox = it.next(); fox.hunt(newFoxes); if(! fox.isAlive()) { Very similar code!! Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
19
Improve with the use of an abstract class!
Room for improvement Fox and Rabbit have very strong similarities, but does not use inheritance with a common superclass The update step in Simulator also involves very similar-looking code The Simulator class is tightly coupled to specific classes It knows a lot about the behavior of foxes and rabbits Improve with the use of an abstract class! Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
20
Simulator can now be significantly de-coupled!
The Animal superclass Place common fields and methods in Animal move fields alive, location and field discuss age field later private instance fields initialized in constructor alive set to true location & field passed from Fox & Rabbit via super move existing accessors and mutators isAlive, setDead, getLocation, and setLocation set to protected to allow subclass access add additional accessor method getField also set to protected to allow subclass access Rename methods to support information hiding merge run and hunt to become act Simulator can now be significantly de-coupled!
21
Revised (de-coupled) iteration
for(Iterator<Rabbit> it = rabbits.iterator(); it.hasNext(); ) { Rabbit rabbit = it.next(); rabbit.run(newRabbits); if(! rabbit.isAlive()) { it.remove(); } … for(Iterator<Fox> it = foxes.iterator(); it.hasNext(); ) { Fox fox = it.next(); fox.hunt(newFoxes); if(! fox.isAlive()) { merged for(Iterator<Animal> it = animals.iterator(); it.hasNext(); ) { Animal animal = it.next(); animal.act(newAnimals); if(! animal.isAlive()) { it.remove(); }
22
The act method of Animal
for(Iterator<Animal> it = animals.iterator(); it.hasNext(); ) { Animal animal = it.next(); animal.act(newAnimals); if(! animal.isAlive()) { it.remove(); } Each animal element is of type Animal where Fox & Rabbit are both subtypes of Animal Specific actions for Fox & Rabbit renamed act where Fox will hunt & where Rabbit will run dynamic type determines which method is executed Static type checking requires an act in Animal Define act as abstract method (with header only and no body) which can not and will not ever be executed: abstract public void act(List<Animal> newAnimals); Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
23
Abstract classes and methods
abstract public void act(List<Animal> newAnimals); Abstract methods have abstract in the signature Abstract methods have no body Abstract methods make the class abstract Abstract classes cannot be instantiated no object can be created for an abstract class Concrete subclasses need to complete the implementation overriding methods for abstract methods Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
24
Abstract method to resolve static compilation!
The Animal class for(Iterator<Animal> it = animals.iterator(); it.hasNext(); ) { Animal animal = it.next(); animal.act(newAnimals); if(! animal.isAlive()) { it.remove(); } Abstract method to resolve static compilation! public abstract class Animal { fields omitted /** * Make this animal act - that is: make it do * whatever it wants/needs to do. */ abstract public void act(List<Animal> newAnimals); other methods omitted }
25
What about the age field?
Code duplication in Fox & Rabbit subclasses private int age; … private void incrementAge() { age++; if(age > MAX_AGE) { setDead(); } Why not just move the age field and incrementAge( ) from Fox & Rabbit subclasses to Animal superclass? Use of same class variable but with different values!! Which value should be declared in the superclass? BOTH private static final int MAX_AGE = 40; // Rabbits private static final int MAX_AGE = 150; // Foxes
26
Abstract & concrete methods
Move age and incrementAge( ) to Animal superclass AND change class variable to abstract method call private int age; abstract protected int getMaxAge; public void incrementAge() { age++; if(age > getMaxAge()) { setDead(); } Include concrete getMaxAge method in both the subclasses to execute during dynamic method lookup private static final int MAX_AGE = 40; // Rabbits or public int getMaxAge() // Foxes 150 { return MAX_AGE; }
27
Flexibility with abstraction
Extend simulation to include non-animal participants public abstract class Actor { abstract public void act(List<Actor> newActors); abstract public boolean isActive(); }
28
Selective drawing (multiple inheritance)
Further extension of separating visualization from acting Iterate over separate collections instead of whole field Another superclass Drawable with abstract draw method Drawable actors must inherit from both Actor & Drawable
29
Multiple inheritance A class has more than one immediate superclass
subclass has all features of BOTH superclasses and those defined in itself Each language has its own rules some allow multiple superclasses but … Java forbids it Java interface allows a limited form definitions are abstract with NO competing implementation
30
NO instance fields, constructors or method bodies!!
An Actor interface NO instance fields, constructors or method bodies!! public interface Actor { /** * Perform the actor's regular behavior. newActors List for storing newly created actors. */ void act(List<Actor> newActors); * Is the actor still active? true if still active, false if not. boolean isActive(); } Keyword interface instead of class in the header All methods are abstract no method bodies permitted abstract keyword is therefore not needed No constructors All method headers have public visibility no public keyword necessary Only public constant class fields are allowed public, static and final keywords are omitted
31
Classes implement an interface
public class Fox extends Animal implements Drawable { ... } A class can extend one abstract class and implement many interfaces - BUT extends clause must be first in the header public class Hunter implements Actor, Drawable { ... } Hunter inherits the abstract methods of interfaces (i.e. act & draw) BUT it must provide overriding method definitions for all of them OR the class itself must be declared abstract (i.e. Actor) Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
32
Interfaces as types Classes do NOT inherit code from an interface … so why implement them: subclasses become subtypes of the superclass interface type allowing polymorphic variables and method calls so different special cases of objects in subclasses may be treated uniformly as instances of the superclass i.e. Animal & Hunter objects as Actor subtype Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
33
Features of interfaces
All methods are abstract There are no constructors All methods are public All fields are public, static and final Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
34
Interfaces as specifications
Strong separation of functionality from implementation Though parameter and return types are mandated in headers Clients interact independently of the implementation But clients can choose their own alternative implementations of the same functionality Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
35
Alternative implementations
List interface and its subclasses ArrayList & LinkedList List interface specifies the full functionality Without any implementations Only parameter and return types ArrayList & LinkedList have own implementations two implementations differ in function efficiency ArrayList faster for random access to middle elements LinkedList faster for inserting or deleting elements Easy to implement both using List interface only when new list is created use specific implementation List<Type> myList = new ArrayList<Type>( );
36
foxes-and-rabbits-graph
SimulatorView interface and implementing classes SimulatorView changed to an interface Without any implementations Implement both views using SimulatorView interface GridView is identical to previous SimulatorView GraphView easily displays another view of the collection In Simulator, concrete class GridView and GraphView objects stored in collection of SimulatorView objects only interface type is used to communicate with them
37
The Class class A Class object associated with Class in the Object is returned by getClass() OR … the .class suffix also provides the Class object: Fox.class Use String getName() for the class name Mapping in SimulatorView to associate each animal type with a color in the field: private Map<Class, Color> colors; At view setup, Simulator constructor calls: view.setColor(Rabbit.class, Color.ORANGE); view.setColor(Rabbit.class, Color.ORANGE); Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
38
Abstract class or interface?
Class intended to contain implementations for some methods: Use abstract classes If either abstract class or interface will work: Choose interface preferably allows multiple inheritance creates more flexibility and extenibility Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
39
Event-driven simulations
Time passing in equal-length steps in the simulation time-based or synchronous Some actors do nothing for many “time steps” baby rabbits repeatedly asked to breed but unable What is the most appropriate size for a time step? Various actions may require different time steps frequently eat and move … but less often birth How to decide on the appropriate time steps? Maintain an uneven schedule of future events event-based or asynchronous An event occurs at time t … but others t+2…t+8… at birth, an animal’s old-aged death is scheduled All events stored in a time-ordered queue newly scheduled events not necessarily at the end other items obsolete (i.e. rabbit eaten by fox)
40
Event-driven or time-driven
Which should be used? Large systems and large amounts of data involved event-based or asynchronous Time-based visualizations where time flows evenly time-based or synchronous
41
Review Inheritance can provide shared implementation
Concrete and abstract classes Inheritance provides shared type information Classes and interfaces Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
42
Review Abstract methods allow static type checking without requiring implementation Abstract classes function as incomplete superclasses No instances Abstract classes support polymorphism Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
43
Review Interfaces provide specification without implementation
Interfaces are fully abstract Interfaces support polymorphism Java interfaces support multiple inheritance Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.