Further abstraction techniques Abstract classes and interfaces 6.0.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Further abstraction techniques Abstract classes and interfaces 5.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.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
Chapter 10 Classes Continued
Further abstraction techniques Abstract classes and interfaces 3.0.
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)
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
CC1007NI: Further Programming Week 3 Dhruba Sen Module Leader (Islington College)
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.
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
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.
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Object Oriented Programming
Further abstraction techniques
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.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Abstract Classes and Interfaces Week 17.  Computer simulations  Abstract methods  Abstract classes  Interfaces  Multiple inheritance Abstract Classes.
Programming in java Packages Access Protection Importing packages Java program structure Interfaces Why interface Defining interface Accessing impln thru.
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
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 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)
(c) University of Washington05-1 CSC 143 Java Abstract Classes and Frameworks Reading: Ch. 11.
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.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
Understanding class definitions Exploring source code 6.0.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Functional Processing of Collections (Advanced) 6.0.
6.0 Objects First with Java A Practical Introduction using BlueJ David J. Barnes Michael Kölling.
Comp1004: Object Oriented Design I Abstract Classes and Interfaces.
11 Further abstraction techniques
Modern Programming Tools And Techniques-I
Objects First with Java A Practical Introduction using BlueJ
Inheritance and Polymorphism
Functional Processing of Collections (Advanced)
Interface.
COS 260 DAY 10 Tony Gauvin.
COS 260 DAY 2 Tony Gauvin.
Interfaces.
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Advanced Java Programming
COS 260 DAY 19 Tony Gauvin.
Java Inheritance.
COS 260 DAY 23 Tony Gauvin.
Chapter 14 Abstract Classes and Interfaces
COS 260 DAY 23 Tony Gauvin.
Further abstraction techniques
Presentation transcript:

Further abstraction techniques Abstract classes and interfaces 6.0

2 Main concepts to be covered Abstract classes Interfaces Multiple inheritance © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

3 Simulations Programs regularly used to simulate real-world activities: –city traffic; –the weather; –nuclear processes; –stock market fluctuations; –environmental impacts; –space flight. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

5 Benefits of simulations Support useful prediction. –E.g., the weather. Allow experimentation. –Safer, cheaper, quicker. Our example: –‘How will the wildlife be affected if we cut a highway through the middle of this national park?’ © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

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... © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

7 The foxes-and-rabbits project © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

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. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

9 Modeling the environment Field –Represents a 2D field. Location –Represents a 2D position in the environment. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

10 Monitoring the simulation SimulatorView –Presents a view of the environment. FieldStats, Counter –Maintain statistics. Randomizer –Supports reproducibility. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

11 Example of the visualization © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

12 A Rabbit’s state © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. public class Rabbit { Static fields omitted. // Individual characteristics (instance fields). // The rabbit's age. 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. }

13 A Rabbit’s behavior Managed from the run method. Age incremented at each simulation ‘step’. –A rabbit could die at this point. Rabbits that are old enough might breed at each step. –New rabbits could be born at this point. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

14 Rabbit simplifications Rabbits do not have different genders. –In effect, all are female. The same rabbit could breed at every step. All rabbits die at the same age. Others? © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

15 A Fox’s state © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. public class Fox { Static fields 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, which is increased // by eating rabbits. private int foodLevel; Methods omitted. }

16 A Fox’s behavior Managed from the hunt method. Foxes also age and breed. They become hungry. They hunt for food in adjacent locations. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

17 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? © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

18 The Simulator class Three key components: –Setup in the constructor. –The populate method. Each animal is given a random starting age. –The simulateOneStep method. Iterates over separate populations of foxes and rabbits. Two Field objects are used: field and updatedField. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

19 The update step © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. for(Iterator it = rabbits.iterator(); it.hasNext(); ) { Rabbit rabbit = it.next(); rabbit.run(newRabbits); if(! rabbit.isAlive()) { it.remove(); } … for(Iterator it = foxes.iterator(); it.hasNext(); ) { Fox fox = it.next(); fox.hunt(newFoxes); if(! fox.isAlive()) { it.remove(); }

20 Room for improvement Fox and Rabbit have strong similarities but do not have a common superclass. The update step involves similar- looking code. The Simulator is tightly coupled to specific classes. –It ‘knows’ a lot about the behavior of foxes and rabbits. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

21 The Animal superclass Place common fields in Animal : –age, alive, location Method renaming to support information hiding: –run and hunt become act. Simulator can now be significantly decoupled. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

22 Revised (decoupled) iteration © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. for(Iterator it = animals.iterator(); it.hasNext(); ) { Animal animal = iter.next(); animal.act(newAnimals); // Remove dead animals from simulation if(! animal.isAlive()) { it.remove(); }

23 The act method of Animal Static type checking requires an act method in Animal. There is no obvious shared implementation. Define act as abstract: © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. abstract public void act(List newAnimals);

24 Abstract classes and methods Abstract methods have abstract in the signature. Abstract methods have no body. Abstract methods make the class abstract. Abstract classes cannot be instantiated. Concrete subclasses complete the implementation. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

25 The Animal class © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. 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 newAnimals); other methods omitted }

26 Further abstraction © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

27 Selective drawing (multiple inheritance) © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

28 Multiple inheritance Having a class inherit directly from multiple ancestors. Each language has its own rules. –How to resolve competing definitions? Java forbids it for classes. Java permits it for interfaces. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

29 An Actor interface © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. public interface Actor { /** * Perform the actor's regular behavior. newActors A list for storing newly created * actors. */ void act(List newActors); /** * Is the actor still active? true if still active, false if not. */ boolean isActive(); }

30 Classes implement an interface © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. public class Fox extends Animal implements Drawable {... } public class Hunter implements Actor, Drawable {... }

31 Interfaces as types Implementing classes are subtypes of the interface type. So, polymorphism is available with interfaces as well as classes. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

32 Features of interfaces Use interface rather than class in their declaration. They do not define constructors. All methods are public. All fields are public, static and final. (Those keywords may be omitted.) Abstract methods may omit abstract. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

33 Features of interfaces Methods marked as default have a method body – they are not abstract. Methods marked as static have a method body. Default and static methods could complicate multiple inheritance of interfaces. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

34 Default methods Introduced in Java 8 to adapt legacy interfaces; e.g., java.util.List. Classes inheriting two with the same signature must override the method. Syntax for accessing the overriden version: InterfaceType.super.method(…) © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

35 Interfaces as specifications Strong separation of functionality from implementation. –Though parameter and return types are mandated. Clients interact independently of the implementation. –But clients can choose from alternative implementations. List, Map and Set are examples. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

36 Alternative implementations © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

37 Functional interfaces and lambdas (advanced) Interfaces with a single abstract method are functional is the associated annotation. A lambda may be used where a functional interface is required. java.util.function defines some functional interfaces. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

38 Common functional interfaces (advanced) Consumer : for lambdas with a void return type. BinaryOperator : for lambdas with two parameters and a matching result type. Supplier : for lambdas returning a result. Predicate : returns a boolean. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

39 Functional interfaces (advanced) Having functional types for lambdas means we can assign them to variables, or pass them as parameters; e.g.: © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved. BinaryOperator aka = (name, alias) -> { return name + " (AKA " + alias + ")"; };

40 The Class class A Class object is returned by getClass() in Object. The.class suffix provides a Class object: Fox.class Used in SimulatorView : Map colors; String getName() for the class name. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

41 Review Inheritance can provide shared implementation. –Concrete and abstract classes. Inheritance provides shared type information. –Classes and interfaces. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

42 Review Abstract methods allow static type checking without requiring implementation. Abstract classes function as incomplete superclasses. –No instances. Abstract classes support polymorphism. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.

43 Review Interfaces provide specification – usually without implementation. –Interfaces are abstract apart from their default methods. Interfaces support polymorphism. Java interfaces support multiple inheritance. © 2017 Pearson Education, Inc. Hoboken, NJ. All rights reserved.