Slides_Java02
Transcrição
Slides_Java02
Outline • Inheritance – – – – Class Extension Overriding Methods Inheritance and Constructors Polymorphism • Abstract Classes • Interfaces 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 1 OOP Principles • Encapsulation – Methods and data are combined in classes – Not unique to OOP: Ada supports class-based programming • Information Hiding – Implementation of a class can be changed without affecting clients – Not unique to OOP: Ada supports information hiding through packages • Inheritance – Classes can be adapted through inheritance • Polymorphism – Substitution rule: Subtypes must fulfill the contract of its base type 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 2 Inheritance • Inheritance in Java – New classes can be defined by extending existing classes – The extension inherits all fields and methods from the base class – New fields, methods and constructors may be added • Example – Figure Contains position (x, y) Provides method move(dx, dy), getX(), getY() – Circle Additional field: radius Additional method: getRadius() – Rectangle Additional fields: width / height Additional method: getArea() 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 3 Inheritance in Java • Figure class Figure { private int x, y; public int getX() { return x; } public int getY() { return y; } public void move(int dx, int dy) { x += dx; y += dy; } } • Circle • Rectangle class Circle extends Figure { private int radius; class Rectangle extends Figure { private int width, height; public int getRadius(){ return radius; } public int getArea() { return width * height; } } 4 March 2016 } (C) Hochschule für Technik Fachhochschule Nordwestschweiz 4 Inheritance in Java • Extension – Class Rectangle inherits the fields x and y – Class Rectangle declares new fields width and height – Class Rectangle inherits the method move(int dx, int dy) – Class Rectangle declares the new method getArea() Rectangle r = new Rectangle(); r.x = 5; r.y = 5; r.width = 20; r.height = 10; r.move(10, 5); r.getArea(); 4 March 2016 r int int int int x = 15 5 y = 10 5 width = 20 height = 10 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 5 Inheritance in Java • Extension class D extends B { … } – Keyword extends – Fields and methods are inherited, i.e. are available in the extension and can be accessed / called – Only one base class can be specified to inherit from; if no base class is specified class Object is the base class Object Animal Mammal 4 March 2016 Figure Rectangle Circle (C) Hochschule für Technik Fachhochschule Nordwestschweiz 6 Inheritance in General • Code Inheritance (Extension, Subclassing) Implementation Aspect – Figure has fields x/y and method move – Rectangle inherits x/y/move and adds additional fields and methods Figure.Attributes Rectangle.Attributes • Interface Inheritance (Specialization, Subtyping) Design Aspect – Every rectangle is a figure, but not every figure is a rectangle, i.e. interface specification is reused (and specialized) – Type defines a set of objects: Figures Rectangles 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 7 Inheritance in General • Code Inheritance (Extension, Subclassing) – Subclasses add new fields & methods – Subclasses have more (specialized) attributes & operations Implementation Aspect Figure Rectangle Circle • Interface Inheritance (Specialization, Subtyping) – Types define a set of objects – Subtypes are specializations Figure Circle 4 March 2016 Design Aspect Rectangle (C) Hochschule für Technik Fachhochschule Nordwestschweiz 8 Interface Inheritance (Subtyping) • Type – Type defines a set of values and a set of permissible operations – Type only defines behavior, but not implementation – Types are used in declarations of reference variables e.g. Figure f; – Java: Types are specified by classes. • Subtyping – – – – Types can be specialized Subtype defines a is-a relationship The operations defined for a type can also be applied for a subtype Java: Subtyping is defined by subclassing, i.e. each subclass also defines a subtype (i.e. no private inheritance!!!) 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 9 Method Overriding • Method Overriding – If in extension class a method is declared with the same signature as in the base class, then the method in the base class is overridden Overriding # overloading !!! if signatures differ, method in base class is NOT overwridden but overloaded! – Overwriting method hides overridden method – Hidden method can be called with a supercall super.<methodname>(arguments) • @Override – An overriding method can (should) be marked with the @Override annotation 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 10 Method Overriding • Inherited methods may be overridden class Rectangle extends Figure { private int w, h; @Override public void draw() { drawRectangle(x, y, w, h); } } class TextBox extends Rectangle { private String text; @Override public void draw() { super.draw(); drawString(x+5, y+5, text); } } 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 11 Inheritance: Initialization • Initialization of base class – What happens when new instance of an extended class is created? Base class and extended class have to be initialized Base class is initialized before extended class is initialized (because extended class may depend on fields in the base class) Constructor of extended class first calls default constructor of base class – What happens if such a constructor is not available? • Explicit invocation of a constructor in the base class – with super(…) a constructor in the base class can be explicitly called super(…) is only allowed as first statement in a constructor a corresponding constructor must be provided by the base class super(…) and this(…) exclude each other 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 12 Inheritance: Initialization Example class Figure { private int x, y; public Figure(int x, int y) { this.x = x; this.y = y; } public void move(int dx, int dy) { x += dx; y += dy; } public void draw() { } } class Rectangle extends Figure { private int w, h; public Rectangle(int x, int y, int w, int h) { super(x, y); this.w = w; this.h = h; } public Rectangle(int w, int h) { this(0, 0, w, h); } public int getArea() { return w*h; } public int getWidth() { return w; } public void draw() { /* draw Rectangle */ } } 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 13 Inheritance: Initialization • Implicit Initialization of Base Class – If neither a this nor a super call is declared in a constructor, then the default constructor (no arguments) of the base class is called. – if the default constructor does not exist: error! • Default Constructor (revisited) class A { } 4 March 2016 => class A { A(){ super(); } } (C) Hochschule für Technik Fachhochschule Nordwestschweiz 14 Inheritance in Java: Base Class Object • Object (java.lang.Object) – Direct or indirect base class of all classes (single rooted class tree) – Methods 4 March 2016 String toString() returns a string representation of the object boolean equals(Object obj) returns whether obj is "equal to" this one int hashCode() returns a hash code value for the object void finalize() called by the GC (last wish) Object clone() returns a copy of this Class getClass() returns the runtime class of an object. Synchronization primitives • void notify() • void notifyAll() • void wait() • void wait(long timeout) • void wait(long timeout, int nanos) • void notifyAll() (C) Hochschule für Technik Fachhochschule Nordwestschweiz 15 Inheritance in Java: Base Class Object • Default implementations public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } public boolean equals(Object obj) { return this == obj; } – All other methods are declared as native (implemented by the JVM) – If you want to have another behavior, then override methods 4 March 2016 String toString() boolean equals(Object obj) int hashCode() void finalize() Object clone() // same signature!!!! (C) Hochschule für Technik Fachhochschule Nordwestschweiz 16 Polymorphism • Polymorphic Assignment – Instances of extension classes can be assigned to variables of base type Figure f = new Rectangle(0, 0, 4, 2); Static type of f: Figure • Static type = type of variable • Static type of a variable never changes Dynamic type of f: Rectangle • Dynamic type = type of referenced object • Dynamic type of a variable may change with every assignment Dynamic Type Static Type 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 17 Polymorphism • Polymorphic Dispatch – Dynamic type defines which method is called Figure f = new Rectangle(0, 0, 4, 2); f.draw(); // => Rectangle’s draw is called f = new Circle(5, 5, 10); f.draw(); // => Circle’s draw is called Figure[] figs = new Figure[]{ new Rectangle(0,0,4,2), new Circle(5,5,10) }; for(int i=0; i < figs.length; i++) { figs[i].draw(); } • Polymorphism: Definition – Polymorphism allows operations to be performed on objects without needing to know which class the object belongs to, provided that we can guarantee that the class implements the specified type 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 18 Polymorphism • Static Type – In Java polymorphism is controlled by type declarations Figure f; – When a variable is declared as being of a particular type, then we have a language-enforced guarantee that any object referenced by that variable will have (at least) all the features of that type. f.move(2, 3); f.draw(); // works (as expected) – Static type defines whether a method call is possible method has to be defined in type declaration static type is responsible for method overload resolution! • Dynamic Type – Dynamic type is the type of the referenced instance – Dynamic type defines which method is executed (dynamic dispatch) 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 19 Polymorphism • Type test: instanceof – with the instanceof operator the dynamic type can be inspected if( f instanceof Rectangle)... // returns true if dynamic type of f is // Rectangle (or an extension thereof) // null instanceof C => false • Type casts: C-style casts (Rectangle) f // // // // // changes the static type of expression f to Rectangle; a run-time error is thrown if the dynamic type of f is not a Rectangle (or an extension thereof) – this type cast allows to access the methods / attributes defined for Rectangle only (and not for Figure). 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 20 Polymorphism • Figure f = new Rectangle(); • Rectangle r = (Rectangle) f; r f Rectangle x y w h 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 21 Polymorphism • Liskov Substitution Principle – If S is a subtype of T, then objects of type T may be replaced with objects of type S without altering the correctness of the program – Whenever you work with an instance of type T, you should not be surprised if you effectively work with an instance of type S – An instance of type S can be used at all places where an instance of type T is expected • Consequences – Overriding methods need to satisfy the rules specified by the base class – Overriding methods may do more and expect less 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 22 Discussion: Which is Subtype of What • Square class Square { int x, y, w; void setWidth(int w) { this.w = w; } int getWidth() { return w; } } • Rectangle class Rectangle { int x, y, w, h; void setWidth(int w) { this.w = w; } void setHeight(int h) { this.h = h; } int getWidth() { return w; } int getHeight() { return h; } } 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 23 Outline • Inheritance • Abstract Classes • Interfaces 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 24 Figure Example class Figure { int x, y; void draw( ) { } } class Rectangle extends Figure { int w, h; @Override void draw( ) { /* draw Rectangle at (x,y) */ } } Text 4 March 2016 class TextBox extends Rectangle { String text; @Override void draw( ) { Screen.drawText(x, y, text); super.draw(); • How to implement draw in Figure? } • Do we need draw at all here? } (C) Hochschule für Technik Fachhochschule Nordwestschweiz 25 Abstract Methods • Abstract methods only define a signature public abstract void draw( ); – have no body – have to be implemented in subclasses • Abstract methods are useful for polymorphic calls – They define the methods which must be provided by subclasses • Abstract methods can only be declared in abstract classes 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 26 Abstract Classes • Abstract classes are declared with the abstract keyword public abstract class Figure { private int x, y; public abstract void draw( ); } • Abstract classes cannot be instantiated, but – may have attributes, and thus – may have constructors • Classes which extend abstract classes – have to override all abstract methods – … or have to be declared as abstract if not all abstract methods are overridden 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 27 Abstract classes may have attributes Figure Example Abstract classes may have constructors public abstract class Figure { private int x, y; public Figure(int x, int y) { Abstract classes this.x = x; this.y = y; may have non} abstract methods public int getX() { return x; } public int getY() { return y; } public void move(int dx, int dy) { x += dx; y += dy; } public abstract void draw( ); } public class Square extends Figure { private int size; public Square(int x, int y, int w){ super(x,y); size = w;} public int getSize() { return size; } @Override public void draw( ) { drawRectangle(getX(), getY(), w, w); } } 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 28 Abstract Classes: Remarks • Abstract Classes and Methods – An abstract method must be declared in an abstract class – An abstract class must not necessarily contain an abstract method! Useful to declare classes that cannot be instantiated (but extended) • Figure[ ] figures = new Figures[10] – Arrays of an abstract base type may be instantiated since NO instances are created – figures-array can be filled with references to concrete figures figures[0] figures[1] … for(Figure f.draw( } 4 March 2016 = new Square(0, 0, 10); = new Rectangle(10, 10, 20, 10); f : figures) { ); (C) Hochschule für Technik Fachhochschule Nordwestschweiz 29 Abstract Classes: Remarks • Abstract Methods can always be called – The concrete instances implement these methods – Interesting case: calling abstract methods within an abstract class abstract class OutputStream { public abstract void write(byte b); // implementation depends on stream type, i.e. // SocketStream, FileStream, etc. public void write(byte[] buf){ for(int i=0; i<buf.length; i++) write(buf[i]); } } 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 30 Abstract Classes: Remarks • private – Private methods cannot be declared abstract, as private methods cannot be overridden. • static – Static methods cannot be declared abstract, as static methods can never be overridden. 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 31 Outline • Inheritance • Abstract Classes • Interfaces 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 32 Interfaces • Characteristics – No implementation All methods are by default public and abstract – No state All attributes are by default public, static and final (i.e. constants) – No constructors • Example public interface Figure { int getX(); int getY(); void move(int dx, int dy); void draw(); } 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 33 Interfaces (since Java 8) • Default methods – Since Java8 interfaces may contain default methods – Default methods can access other methods – Allows to extend interfaces without breaking existing classes • Example public interface Figure { int getX(); int getY(); void move(int dx, int dy); void draw(); default void moveTo(int x, int y) { move(x - getX(), y - getY()); } } 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 34 Implementation of Interfaces • implements – Interfaces are implemented in classes All methods defined in the declared interfaces have to be implemented … or the class has to be declared abstract class Rectangle implements Figure { private int x, y, w, h; public Rectangle(int x, int y, int w, int h) { this.x = x; this.y = y; this.w = w; this.h = h; } @Override public void draw( ) { drawRectangle(x,y,w,h); } @Override public void move(int dx, int dy) { x+=dx; y+=dy; } @Override public int getX() { return x; } @Override public int getY() { return y; } public int getWidth() { return w; } public int getHeight() { return h; } } 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 35 Interface and Abstract Base Class • Abstract Figure – may be used as base class for concrete Figures public abstract class AbstractFigure implements Figure { private int x, y; public AbstractFigure(int x, int y) { this.x=x; this.y=y; } @Override public int getX() { return x; } @Override public int getY() { return y; } @Override public void move(int dx, int dy) { x+=dx; y+=dy; } } • Concrete Figures extend abstract base class public class Rectangle extends AbstractFigure { private int w, h; public Rectangle(int x, int y, int w, int h) { super(x, y); this.w=w; this.h=h; } @Override public void draw( ) { drawRectangle(x, y, w, h); } } 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 36 Interface and Abstract Base Class • Interface: • Abstract class: provides a type semi finished component – Contains default implementations which can be used in subclasses which can be overridden in subclasses • Concrete class: 4 March 2016 complete component (C) Hochschule für Technik Fachhochschule Nordwestschweiz 37 Implementing Multiple Interfaces • A class can extend only one class (implicitly class Object) • A class can implement several interfaces – Example: Polygon provides polygon-specific methods interface Polygon { boolean isConvex(); } – Rectangle implements both interfaces Figure (implemented directly or inherited over AbstractFigure) Polygon class Rectangle AbstractFigure implements class Rectangleextends implements Figure, Polygon { Polygon { @Override draw( ) { ){ … }….} @Overridepublic publicvoid void draw( …… @Override isConvex() { … }… } @Overridepublic publicboolean boolean isConvex(){ } 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 38 Interface Extension • Interfaces may be extended – all methods of the base interface are inherited – additional methods can be specified interface Polygon { boolean isConvex(); } interface Polygon2 extends Polygon { Line[] getLines() } • Interfaces may extend multiple interfaces (multiple subtyping) – methods with same name / argument list must have the same return type interface PolygonFigure extends Figure, Polygon { ... } 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 39 Interface Variables • Interface type can be used to declare reference variables – similar to (abstract) classes: reference refers to a class which implements the interface – only the methods declared in the interface are available – instanceof can be used to check the dynamic type • Examples Dynamic Type Static Type – Variable Figure f; // interface type f = new Rectangle(0, 0, 300, 200); f.move(30, 30); – Parameter void addFigure(Figure f) // can be called with any class implementing interface Figure 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 40 Interface Variables • Examples public interface Figure { int getX(); int getY(); void move(int dx, int dy); } interface Polygon { boolean isConvex(); } public class Rectangle implements Figure, Polygon { … } 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 41 Interface Variables • Examples Rectangle r = new Rectangle(0, 0, 50, 30); Figure f = r; // Rectangle implements Figure Polygon p = r; // and Polygon interfaces f.move(20, 20); f.isConvex(); // works // does not work f instanceof Polygon // returns true as the refe// renced object implements // the interface Polygon ((Polygon)f).isConvex(); // works as the referenced // Object implements the // interface Polygon 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 42 Interfaces vs. Abstract Classes • Abstract Class – Abstract class defines a type can be used in declarations – Abstract methods only define signature / behavior • Interface – Interface defines a type can be used in declarations – Methods in interface definition only define signature / behavior have to be implemented in extending class have to implemented in an implementing class abstract class cannot be instantiated interface cannot be instantiated – Abstract class may contain – Interface = pure abstract class attributes no attributes method implementations no code – A class may extend only one abstract class 4 March 2016 – A class may implement several interfaces (C) Hochschule für Technik Fachhochschule Nordwestschweiz 43 Why Interfaces? • Allows to define Interfaces (collection of Methods) independent of a type hierarchy interface Size { int getWidth(); int getHight(); } – this interface might be implemented by Figures and Cars without the need to extend Figures and Cars from a common subclass (=> unnatural) Size Figure 4 March 2016 Vehicle Car Figure Size Car (C) Hochschule für Technik Fachhochschule Nordwestschweiz 44 Marker Interfaces • Definition – Interface without methods and constants (=> empty interface) – Can be used to add an attribute to a class (jdk1.5: Attributes) • Example: java.util.RandomAccess – Definition package java.util; interface RandomAccess { } – Declaration class ArrayList implements RandomAccess { … } // ArrayList declares to support random access – Test with instanceof Operator if (list instanceof RandomAccess) { … } 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 45 Summary • Subclassing = Implementation Inheritance – Code inheritance – Implementation aspect • Subtyping = Interface Inheritance – Inheritance of behavioral specification – Design aspect • Java – Class defines type and implementation if the type of a variable is a class name, then the variable may reference an object of the named class or any subclasss of that class – Interface defines type if the type of a variable is defined by an interface name, then the variable may reference an object of any class which implements that interface 4 March 2016 (C) Hochschule für Technik Fachhochschule Nordwestschweiz 46