Java Interfaces PDF
Document Details
Uploaded by StatelyAgate7771
Dr. Bruno Schäffer
Tags
Summary
These lecture notes cover Java interfaces, including their properties, behavior, and usage. The notes also explore functional interfaces, tagging interfaces, and constant interfaces. The document further discusses Groovy Traits, Abstract Classes, and the practical application in Java code examples, and how they can be used to implement specific functionality in the given examples. Finally, the takeaway points related to the abstract concept of interfaces and abstract classes are presented.
Full Transcript
Java – Interfaces • • „Class“ which declares only behavior • • • • Interface defines a type, most abstract type specification Behavior: abstract methods + default methods (since Java 8) State is not allowed (except constants) Since Java 9 private methods are allowed in an interface (supports fa...
Java – Interfaces • • „Class“ which declares only behavior • • • • Interface defines a type, most abstract type specification Behavior: abstract methods + default methods (since Java 8) State is not allowed (except constants) Since Java 9 private methods are allowed in an interface (supports factorization) Class can inherit from 0-1 classes and implement 0-n interfaces public interface IScalable { void drawScaled(Graphics g, int scale); } public class ScalableBox extends Box implements IScalable { void drawScaled(Graphics g, int scale) {…}; } • public class ScalableView extends View { void addScalableShape(IScalable scalable) {…}; } Use interfaces for static type declarations whenever possible! Dr. Bruno Schäffer © 2023 Object-Oriented Software Development – Principles 37 Java – Interfaces Library 1.0 public interface X { void x(); } My Code public class A implements X { public void x() {…} ; } Dr. Bruno Schäffer © 2023 Library 2.0 public interface X { void x(); void y(); } My Code public class A implements X { public void x() {…}; } " Object-Oriented Software Development – Principles 38 Java – Interfaces • Functional interface ! • • • Contains exactly one abstract method (and 0-n default methods) Specifies type of a lambda expression May be annotated with @FunctionalInterface @FunctionalInterface interface IConverter<F, T> { T convert(F from); } //… IConverter<String, Integer> stringToInt = (from) -> Integer.valueOf(from); IConverter<String, Float> stringToFloat = Float::valueOf; Integer i = stringToInt.convert("4711"); Float f = stringToFloat.convert("4711.3412"); Dr. Bruno Schäffer © 2023 Object-Oriented Software Development – Principles 39 Java – Interfaces • Tagging (or marker) interface ! • • • Empty interface (no method declarations) Marking a class to be eligible for being processed by some other class Examples • • • • java.lang.Cloneable - Instances (of classes which are marked as Cloneable) may be copied Default implementation Object::clone is used java.io.Serializable - Instances may be serialized Marker annotations (as an alternative) do not provide compile time support! Constant interface " • • • • Namespace convenience JDK example: java.io.ObjectStreamConstants Implementation detail becomes part of the class’ exported API Since Java 5: use static import instead (class defines constants) Dr. Bruno Schäffer © 2023 Object-Oriented Software Development – Principles 40 Groovy Traits • • • Lightweight multiple inheritance (“interfaces on steroids”) Traits may define state and behavior Used for • • Behavior composition (inheritance at compile time) Run-time implementation of interfaces class Person { String firstName = "Jonathan" String lastName = "Pine" String name() { return "$firstName $lastName"} } Groovy trait FirstName { String firstName() { return firstName } } FirstName fn = new Person() as FirstName assert fn.firstName() == “Jonathan" • Naming conflict resolution (diamond problem) • • Last trait wins State is shared if it is inherited more than once (like virtual inheritance in C++) Dr. Bruno Schäffer © 2023 Object-Oriented Software Development – Principles 41 Abstract Classes • • • • Purpose: • • • Define common structural and functional properties Designed for subtyping, not for instance creation Should be used as an implementation aid, not as a modeling tool Factorization • • • Common properties of subclasses are defined in an abstract class Inheritance allows to adapt or implement these properties Implementation of a system can be based on abstract classes/interfaces Facilitate the implementation of concrete classes • • Several concrete methods can be based on a few abstract methods Example: comparison of objects All comparison methods can be based on “=” and “>” ➜ Small inheritance interface, comprehensive usage interface Facilitates comprehensibility of a class hierarchy Dr. Bruno Schäffer © 2023 Object-Oriented Software Development – Principles 42 Abstract Classes in Java • • Abstract method • • • Only the signature is defined Implementation is left to derived classes Abstract method implies an abstract class (explicit "abstract" required for class) Abstract class • • • Explicitly defined as an abstract class Can contain 0-n abstract methods Instance / class variables may be provided public abstract class Shape { private Rectangle coordinates; public abstract void draw(Graphics g); public void setCoordinates(Rectangle r) {coordinates = r;} public Rectangle getCoordinates() {return coordinates;} } Dr. Bruno Schäffer © 2023 Object-Oriented Software Development – Principles 43 Abstract Classes and Interfaces • • • Interfaces are more versatile than abstract classes • • Class can only inherit from a single abstract class but Inherit from multiple interfaces Interfaces should be as small as possible • • • • • Methods of an interface are abstract (except default methods) Implementing class must implement all non-default methods of its interfaces Small interfaces ease implementability and substitutability (providing alternative implementations) Small interfaces encourage reuse See also SOLID: interface segregation principle Combining abstract classes and interfaces • • • • Abstract class “implements” interface Methods are not abstract but implementation is empty Client may: • • Implement interface ➜ forced to implement all methods Inherit from abstract class ➜ override only required (abstract) methods Since Java 8 the combination interface/abstract class has been mostly superseded by interfaces with default methods Dr. Bruno Schäffer © 2023 Object-Oriented Software Development – Principles 44 Abstract Classes and Interfaces • Example from the Java class library public interface MouseListener extends EventListener { void mouseClicked(MouseEvent e); void mouseEntered(MouseEvent e); void mouseExited(MouseEvent e); void mousePressed(MouseEvent e); void mouseReleased(MouseEvent e); } public abstract public void public void public void public void public void } Dr. Bruno Schäffer © 2023 class MouseAdapter implements MouseListener { mouseClicked(MouseEvent e) {}; mouseEntered(MouseEvent e) {}; mouseExited(MouseEvent e) {}; mousePressed(MouseEvent e) {}; mouseReleased(MouseEvent e) {}; Object-Oriented Software Development – Principles 45 Abstract Classes and Interfaces • • • • • Adding abstract methods breaks clients • • • Major roadblock for evolving libraries Add only non-abstract methods (or default methods) if possible Derived class or interface might help in some cases Develop against interfaces | abstract classes! • • Interfaces protect from changes since they have no implementation Use interfaces | abstract classes for (variable | parameter) declaration Abstract coupling between classes • • • Instance variable typed by interface (preferably) or abstract class Refers to concrete instance at run-time (implementation or derived class) Key concept for reusable design (frameworks) Abstractions have to be stable: clients depend on this Concrete implementations may be unstable: clients don’t care Dr. Bruno Schäffer © 2023 Object-Oriented Software Development – Principles 46 Information Hiding • • Goal: abstracting from the implementation • • • Reducing cognitive load (chunking) Minimize coupling between classes Implementation can be changed without impact on the clients Restricted access rights: • Discrimination between clients and derived classes • • Classes within a subsystem Java: public vs. protected • • • Java: public vs. package private C++: friends Accessors hide state implementations (representation of state) • Accessors should be used both by clients and derived classes • Advantages: • • Disadvantages Minimized coupling, state implementation can be replaced • More verbose and inefficient (optimizations are feasible, e.g. Java or Groovy) Dr. Bruno Schäffer © 2023 Object-Oriented Software Development – Principles 47 Information Hiding • Inheritance violates information hiding • Proper overriding requires knowledge about implementation details of base class public MyList { public void add(Object e) { … } public void addAll(Object[] a) { … } } public class InstrumentedList extends MyList { private int addCounter = 0; public int getAddCounter() { return addCounter; } @Override public void add(Object e) { addCounter++; super.add(e); } @Override public void addAll(Object[] a) { addCounter += a.length; super.addAll(c); } } InstrumentedList v = new InstrumentedList(); v.addAll(new String[]{"a", "b", "c"}); //assert fails if MyList::addAll uses MyList::add for adding objects assert v.getAddCounter() == 3; Dr. Bruno Schäffer © 2023 Object-Oriented Software Development – Principles 48 Information Hiding • • State implementation cannot be changed by derived classes Abstract state • • Specification of state by abstract accessors in an interface / abstract base class Implementation of state in implementing/derived class (incl. concrete accessors) public interface ILabelHolder { String getLabel(); void setLabel(String label); //… } public class Button implements ILabelHolder { private String label; public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } //… } Dr. Bruno Schäffer © 2023 Object-Oriented Software Development – Principles 49 Adaptability vs. Unforeseen Changes • Non-Generic (simple) solutions favor time and money at the expense of adaptability • • • Generic (complex) solutions favor adaptability at the expense of time and money Challenge: find the sweet spot between these two extremes What options do we have? public interface IShape { float area(); } public class Rectangle implements IShape { private Point origin; private Point corner; public Point getOrigin() { … } public Point getCorner() { … } public float area() { … } } Dr. Bruno Schäffer © 2023 public class Circle implements IShape { private Point center; private int radius; public Point getCenter() { … } public int getRadius() { … } public float area() { … } } Object-Oriented Software Development – Principles 50 Adaptability vs. Unforeseen Changes • New requirement: clients need center of IShape • Extend interface and implementing classes • • • Only possible if interfaces / classes may be changed Libraries usually don’t allow for changes Add extension outside of interface / classes • • • Open up abstraction, deal with concrete implementations Does not cover new interface implementations New implementations cannot be excluded, though Dr. Bruno Schäffer © 2023 public interface IShape { float area(); Point center(); } public static Point center(IShape s) { if (s instanceof Circle) { return ((Circle)s).getCenter(); } else if (s instanceof Rectangle) { return //compute center based on origin and corner } else { throw new IllegalArgumentException(); } Object-Oriented Software Development – Principles 51 Adaptability vs. Unforeseen Changes • Sealed interface • • • Does not allow new implementations Shields clients from new implementations Clients can safely deal with existing implementations public sealed interface IShape permits Circle, Rectangle { float area(); } public final class Circle implements IShape { //… } public static Point center(IShape s) { return switch(s) { case Circle c -> c.getCenter(); case Rectangle r -> //compute center based on origin and corner } } Dr. Bruno Schäffer © 2023 Object-Oriented Software Development – Principles 52 Adaptability vs. Unforeseen Changes • Provide a mix sealed and non-sealed classes • • Fixed set of sealed classes Non-Sealed class open open for extension public sealed interface IShape permits Shape, Circle, Rectangle { float area(); } public final class Circle implements IShape { //… } public non-sealed abstract class Shape implements IShape { //… } Dr. Bruno Schäffer © 2023 Object-Oriented Software Development – Principles 53 Interfaces and Abstract Classes – Takeaways Interfaces are a cornerstone of solid software design Default methods are crucial for evolutionary design Abstract coupling is a key concept for reusable design Dr. Bruno Schäffer © 2023 Object-Oriented Software Development – Principles 54