Further abstraction techniques

Slides:



Advertisements
Similar presentations
Fields, Constructors, Methods
Advertisements

1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
Further abstraction techniques Abstract classes and interfaces 5.0.
Objects First With Java A Practical Introduction Using BlueJ Improving structure with inheritance 2.0.
Inheritance Inheritance Reserved word protected Reserved word super
Further abstraction techniques Abstract classes and interfaces 1.0.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Understanding class definitions Looking inside classes 3.0.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Understanding class definitions – Part II –. Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
Chapter 10 Classes Continued
Further abstraction techniques Abstract classes and interfaces 3.0.
Understanding class definitions Looking inside classes.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CC1007NI: Further Programming Week Dhruba Sen Module Leader (Islington College)
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
CC1007NI: Further Programming Week 3 Dhruba Sen Module Leader (Islington College)
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
OOP (Java): Abstract/ OOP Objectives – –use a foxes-and-rabbits simulation to introduce abstract classes, interfaces, and multiple.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 3.0.
Objects First With Java A Practical Introduction Using BlueJ Designing applications 1.0.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Designing classes How to write classes in a way that they are easily understandable, maintainable and reusable 5.0.
Refactoring Deciding what to make a superclass or interface is difficult. Some of these refactorings are helpful. Some research items include Inheritance.
Grouping objects Collections and iterators Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling Main.
CS 106 Introduction to Computer Science I 04 / 23 / 2010 Instructor: Michael Eckmann.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Understanding class definitions
Designing applications Main concepts to be covered Discovering classes CRC cards Designing interfaces Patterns Objects First with Java - A Practical.
Object Oriented Programming
Final Review. From ArrayLists to Arrays The ArrayList : used to organize a list of objects –It is a class in the Java API –the ArrayList class uses an.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Abstract Classes and Interfaces Week 17.  Computer simulations  Abstract methods  Abstract classes  Interfaces  Multiple inheritance Abstract Classes.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Programming in java Packages Access Protection Importing packages Java program structure Interfaces Why interface Defining interface Accessing impln thru.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
// Java2101.java This program tests the features of the class. public class Java2101 { public static void main (String args[]) { System.out.println("\nJAVA2101.JAVA\n");
1 COS 260 DAY 21 Tony Gauvin. 2 Agenda Questions? 8 th Mini Quiz corrected –Good results 9 Th Mini Quiz Today –40 min covering Chap 9 Assignment 5 Due.
Object Oriented Programming and Data Abstraction Rowan University Earl Huff.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
1 COS 260 DAY 22 Tony Gauvin. 2 Agenda Questions? 9 th Mini Quiz corrected –Good results Assignment 5 Not corrected yet Assignment 6 Posted (one more)
Further Abstraction Techniques Chapter 10. Abstract Classes There are times when you do not want someone to be able to make an object of your class. For.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
Further abstraction techniques Abstract classes and interfaces 6.0.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
11 Further abstraction techniques
Modern Programming Tools And Techniques-I
Objects First with Java A Practical Introduction using BlueJ
Inheritance and Polymorphism
Understanding class definitions
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
COS 260 DAY 19 Tony Gauvin.
Java Inheritance.
Understanding class definitions
COS 260 DAY 23 Tony Gauvin.
COS 260 DAY 4 Tony Gauvin.
COS 260 DAY 23 Tony Gauvin.
Further abstraction techniques
Improving structure with inheritance
Presentation transcript:

Further abstraction techniques Abstract classes and interfaces 5.0

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

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

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

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

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

The foxes-and-rabbits project Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

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

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

Example of SimulatorView Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling

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

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

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

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

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

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

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)

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

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

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!

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(); }

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

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

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 }

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

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; }

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(); }

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

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

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. * @param newActors List for storing newly created actors. */ void act(List<Actor> newActors); * Is the actor still active? * @return 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

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

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

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

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

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>( );

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

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

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

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)

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

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

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

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