slide1 n.
Skip this Video
Loading SlideShow in 5 Seconds..
George Blank University Lecturer PowerPoint Presentation
Download Presentation
George Blank University Lecturer

George Blank University Lecturer

185 Vues Download Presentation
Télécharger la présentation

George Blank University Lecturer

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. George Blank University Lecturer

  2. Designing to a Java InterfaceThinking abstractly at a high level A Key Java Skill Spyridon Baroulakis George Blank

  3. Introduction When we create a class that matches a specification, we say that the class implements the specification. In this chapter, we will visit four Java constructions for designing classes and connecting them to their collaborating classes. We will see how interfaces tie in with the rest of the constructs and through polymorphism, multiple inheritance, and abstraction enhance the functionality of Java.

  4. Why we need specifications A program is assembled from a collection of classes that must work together. What does that mean? Say you receive a portable CD player as a gift. When you operate the player nothing happens. It requires batteries. Fortunately, a label in the back instructs that you need 2 AA batteries. Once you insert the proper count and type of batteries, the completed “assembly” now operates seamlessly. You do not need to know how power makes it work, just that you need batteries.

  5. Objectives: • Most Important: Learn to use interfaces in Java to think about code before you develop it. (Philosophy) • Learn how to use interfaces in Java (Mechanics) • Learn the differences between interfaces and abstract classes

  6. Why design to an interface? “Designing to a Java Interface” comes from the slogan: “Program to the interface, not the implementation!” When you write a class that depends on another, collaborator class, you should rely on the collaborator’s interface – its specification – and not its coding (its implementation).This way you design classes separately yet the assembled collection works.

  7. Why design to an interface? A higher level of abstraction allows us to utilize methods and classes with a higher degree of commonality. Structures and approaches can be shared in a wider variety of implementations. You can reuse frameworks of the past and improve on functionality without having to make any changes to already existing work. You simply improve on the next iteration.

  8. What are the four constructs Java interfaces, which define specifications that a coded class must implement. Java inheritance (extends), which defines a new class by adding methods onto an already written class. Java abstract classes, which are “incomplete” classes, part specification and part implementation. Java polymorphism, which allows a common set of methods to be implemented between several families of classes.

  9. Java interfaces Interfaces allow functionality to be shared between objects that agree to a contract on how the software should interact as a unit without needing knowledge of how the objects accomplish their task. On the CD player example, you have a contract with the manufacturer that once you press play, you will hear music. You do not know the specifics of how it is accomplished but you know what will happen. You have both agreed on an interface.

  10. Java interfaces An interface is a reference type that can contain only nested types, method signatures and constants. Method bodies are not defined. Can not be instantiated. Can be implemented by other classes. Can be extended by other interfaces. All methods in an interface are automatically public abstract even if not explicitly stated as such.

  11. Java interfaces public interface OperateCar { // declarations of variables int signalTurn(direction,speed); } Note that the method signature has no braces and is terminated by a semicolon. To use an interface you write a class that implements the interface.

  12. Java interfaces public class BMWCar implements OperateCar { int signalTurn(direction,speed){ // proprietary code to signal you are turning } A Toyota manufacturer may have different positioning of the signals on the car, different signal colors, different light intensity, but he is guaranteeing that when you use signalTurnyou will get the same behavior as the BMW car.

  13. Interfaces and Inheritance Java does not permit multiple inheritance like C++. Some people would say that is a weakness of Java, but there is an alternative view that says Java’s interfaces give the advantages of multiple inheritance while avoiding some of the problems. One of the key problems with multiple inheritance is known as the diamond problem. It occurs when a class inherits from two classes with a common ancestor.

  14. The Diamond Problem Engine Ignition Gas Engine Diesel Engine Ignition: spark plugs Ignition: glow plugs Multifuel Engine Ignition: ?????? When a class inherits from two classes that implement common methods in different ways, what does it inherit?

  15. The Diamond Problem abstract class Engine {abstract void Ignition(method)}; class gasEngine extends Engine { void Ignition(spark_plugs); } class dieselEngine extends Engine { void Ignition(glow_plugs); } class MultiFuelEngine extends gasEngine,dieselEngine { Ignition()???} Runtime cannot determine whether it should invoke Ignition()from gas or diesel engines.

  16. Java’s Solution Java solves the diamond problem by not allowing multiple inheritance from ancestors that have any implementation details. Thus, in Java, classes can only multiply inherit from interfaces and abstract classes that have no implementation details.

  17. Interfaces and Inheritance One interface can inherit another by use of the keyword extends. When a class implements an interface that inherits another interface, it must provide implementations for all methods defined within the interface inheritance chain. Why would we need to have one interface inherit from another instead of modifying the original one? Because all of the implementations we have written in the past would now break. Not all methods would be implemented and we would have to revisit past work.

  18. Interfaces and Inheritance To solve this problem without breaking our previous work, we create a new interface that extends the original one to add new functionality to our design. interface AnyKid { void mayCry();} interface MyKid extends AnyKid { void isSmart();} How do we use the new features that were added in a new class implementation?

  19. Interfaces and Inheritance class MySon implements MyKid { public void mayCry(){System.out.println(“Its ok”);} public void isSmart() {System.out.println(“But he is certainly VERY smart”); } } A class can also implement more than one pertinent interface at the same time but can not inherit from more than one other class.

  20. Inheriting from Two Interfaces For a class to inherit from two interfaces, it must provide implementation for all methods declared in each interface. public class StudentEmployee implements Student, Employee { … implement all methods here. If there is a conflicting method defined in both interfaces the compiler will let us know !

  21. Abstract methods You can declare an object without defining it: Employee john; Similarly you can declare a method without defining it: public abstract void draw(Graphics g); Notice that the body of the method is missing ! A method that has been declared but not defined is an abstract method.

  22. Abstract Classes Any class containing an abstract method is an abstract class. You must declare the class with the keyword abstract. abstract class MyClass { … }; An abstract class is incomplete. Its method bodies have “missing” implementations. You can not instantiate (create a new instance of) an abstract class.

  23. Abstract Classes You can extend (subclass) an abstract class. If the subclass defines all the inherited abstract methods, it is “concrete” and can be instantiated. If the subclass does not define all of the inherited abstract methods, it too needs to be defined abstract. You can define a class to be abstract even if it does not contain any abstract methods. This prevents the class from being instantiated. You can have one or more methods provide full implementation if they are to be used frequently in the same manner.

  24. Why have Abstract Classes? Suppose you wanted to create a class Shape with subclasses Oval, Rectangle, Triangle . You do not want to allow the creation of a Shape Only particular shapes make sense, not generic ones. If Shape is abstract, you can’t create a new Shape . You can create a new Oval, new Rectangle . Abstract classes are used in providing a general category containing specific, “concrete” classes.

  25. Abstract Classes public abstract class Shape { //can define constants public static final double TWO_PI=2*Math.PI; //can declare abstract methods public abstract double computeArea(); public abstract void draw(); //can implement concrete methods public String returnExample() {return “euclidean”;} }

  26. Abstract Classes vs. Interfaces An interface is a list of unimplemented, and therefore abstract, methods. So how does it differ from an abstract class? An interface can not have any methods implemented, whereas an abstract class can. A class can implement many interfaces but can only inherit from one superclass. An interface is not part of the class hierarchy. Unrelated classes can implement the same interface.

  27. Abstract Classes vs. Interfaces Use an abstract class when you want a roadmap for a collection of subclasses. Subclass when you want to extend a class and add some functionality, whether or not the parent class is abstract. Subclass when you must ! (e.g. Applets) Define an interface when there is no common parent class with the desired functionality, and when you want only certain unrelated classes to have that functionality.

  28. Abstract Classes vs. Interfaces Use interfaces as “markers” to indicate something about a class (e.g. Cloneable – be able to make a copy). A common design pattern is to use both an interface and an abstract class depending on the needs of the project. All classes share a single root, the Object class, but there is no single root for interfaces.

  29. Polymorphism Polymorphism, reusability and extendibility tend to be the most common reasons that Java programmers use interfaces. They are closely related because all depend on the flexibility of inheriting from an interface. Designing to an interface often means designing at a high level of abstraction so that methods and classes with a high degree of commonality can share structure and approaches.

  30. Sample Problem Let us say that you are bored watching the fish tank screen saver on your computer and want a view that shows animals walking, birds flying, and fish swimming on your screen at the same time. Here is an approach to designing with interfaces for polymorphism.

  31. Requirements Here we are assuming that walk, swim and fly are all successive animations, but follow different rules. Walking can only take place on land and must stay in contact with the ground. Flying can only take place in the air. Swimming can only take place in the water.

  32. Interface Example interface Mover { void move(); } abstract class Animal implements Mover { abstract public void move(); }

  33. Using the abstract class class Mammal extends Animal { public void move(){ …walk… } } class Bird extends Animal { public void move(){ …fly… } } class Fish extends Animal { public void move(){ …swim… } }

  34. Further investigation The preceding example is just getting started. An animation usually requires several images (different wing positions for a bird, etc.). There may be different kinds of birds. Each animal will have a current image and a current position on the screen. Each move will have a direction, velocity, and length of movement. How would you modify the interface to accommodate these specifications?

  35. References

  36. References

  37. References