Presentation is loading. Please wait.

Presentation is loading. Please wait.

10 More about inheritance

Similar presentations


Presentation on theme: "10 More about inheritance"— Presentation transcript:

1 10 More about inheritance
Objektorienterad programmering d2, förel. 10 10 More about inheritance Polymorphism BK Chap. 11 DAT050, 17/18, lp 2

2 Main concepts to be covered
Objektorienterad programmering d2, förel. 10 Main concepts to be covered method polymorphism static and dynamic type overriding dynamic method lookup protected access Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

3 The inheritance hierarchy
Objektorienterad programmering d2, förel. 10 The inheritance hierarchy Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

4 Objektorienterad programmering d2, förel. 10
Conflicting output Leonardo da Vinci Had a great idea this morning. But now I forgot what it was. Something to do with flying ... 40 seconds ago - 2 people like this. No comments. Alexander Graham Bell [experiment.jpg] I think I might call this thing 'telephone'. 12 minutes ago people like this. What we want Leonardo da Vinci 40 seconds ago people like this. No comments. Alexander Graham Bell 12 minutes ago people like this. What we have Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

5 Objektorienterad programmering d2, förel. 10
The problem The display method in Post only prints the common fields. Inheritance is a one-way street: A subclass inherits the superclass fields. The superclass knows nothing about its subclass’s fields. Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

6 Attempting to solve the problem
Objektorienterad programmering d2, förel. 10 Attempting to solve the problem Place display where it has access to the information it needs. Each subclass has its own version. But Post’s fields are private. NewsFeed cannot find a display method in Post. Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

7 Static type and dynamic type
Objektorienterad programmering d2, förel. 10 Static type and dynamic type A more complex type hierarchy requires further concepts to describe it. Some new terminology: static type dynamic type method dispatch/lookup Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

8 Static and dynamic type
Objektorienterad programmering d2, förel. 10 Static and dynamic type What is the type of c1? Car c1 = new Car(); What is the type of v1? Vehicle v1 = new Car(); Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

9 Static and dynamic type
Objektorienterad programmering d2, förel. 10 Static and dynamic type The declared type of a variable is its static type. The type of the object a variable refers to is its dynamic type. The compiler’s job is to check for static-type violations. for ( Post post : posts ) { post.display(); // Compile-time error. } … print blir osynlig om vi flyttar den till subklasserna, post har ju typen Post. Då klagar givetvis kompilatorn. Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

10 The instanceof operator
Objektorienterad programmering d2, förel. 10 The instanceof operator Used to determine the dynamic type. Recovers ‘lost’ type information. Usually precedes assignment with a cast to the dynamic type: if ( v1 instanceof Car ) { Car c2 = (Car) v1; … access Car methods via c2… } Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

11 Overriding: the solution
Objektorienterad programmering d2, förel. 10 Overriding: the solution display method in both super- and subclasses. Satisfies both static and dynamic type checking. Överskuggning, omdefinition - är inte samma sak som överlagring Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

12 Why static type checking?
Objektorienterad programmering d2, förel. 10 Why static type checking? Has the static type void display()? Object Compiler It has a void display() … whatever it does Static type Dynamic type The compiler only sees the reference variable - not the object Överskuggning, omdefinition - är inte samma sak som överlagring JVM (runtime) JVM relies on the compiler’s type checking Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

13 Objektorienterad programmering d2, förel. 10
Overriding Superclass and subclass define methods with the same signature. Each has access to the fields of its class. Superclass method satisfies static type checking. Subclass method is called at runtime – it overrides the superclass version. What becomes of the superclass version? Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

14 Objektorienterad programmering d2, förel. 10
Method lookup 1 No inheritance. The obvious method is selected. Vid run-time! Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

15 Objektorienterad programmering d2, förel. 10
Method lookup 2 Inheritance but no overriding. The inheritance hierarchy is ascended, searching for a match. Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

16 Distinct static and dynamic types
Objektorienterad programmering d2, förel. 10 Distinct static and dynamic types Post v1; Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

17 Objektorienterad programmering d2, förel. 10
Method lookup 3 Overriding and polymorphism. The ‘first’ version found is used. Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

18 Objektorienterad programmering d2, förel. 10
Method lookup summary The variable is accessed. The object stored in the variable is found. The class of the object is found. The class is searched for a method match. If no match is found, the superclass is searched. This is repeated until a match is found, or the class hierarchy is exhausted. Overriding methods take precedence. Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

19 Objektorienterad programmering d2, förel. 10
Super call in methods Overridden methods are hidden ... ... but we often still want to be able to call them. An overridden method can be called from the method that overrides it. super.method(...) Compare with the use of super in constructors. Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

20 Calling an overridden method
Objektorienterad programmering d2, förel. 10 Calling an overridden method public class PhotoPost extends Post { ... public void display() { super.display(); System.out.println(" [" + filename + "]"); System.out.println(" " + caption); } ... Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

21 Objektorienterad programmering d2, förel. 10
Method polymorphism We have been discussing polymorphic method dispatch. A polymorphic variable can store objects of varying types. Method calls are polymorphic. The actual method called depends on the dynamic object type. Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

22 The Object class’s methods
Objektorienterad programmering d2, förel. 10 The Object class’s methods Methods in Object are inherited by all classes. Any of these may be overridden. The toString method is commonly overridden: public String toString() Returns a string representation of the object. Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

23 Overriding toString in Post
Objektorienterad programmering d2, förel. 10 Overriding toString in Post public String toString() { String text = username + "\n" + timeString(timestamp); if(likes > 0) { text += " - " + likes + " people like this.\n"; } else { text += "\n"; if(comments.isEmpty()) { return text + " No comments.\n"; return text + " " + comments.size() + " comment(s). Click here to view.\n"; Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

24 Objektorienterad programmering d2, förel. 10
StringBuilder Consider using StringBuilder as an alternative to concatenation: StringBuilder builder = new StringBuilder(); builder.append(username); builder.append('\n'); builder.append(timeString(timestamp)); ... return builder.toString(); Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

25 Objektorienterad programmering d2, förel. 10
Overriding toString Explicit print methods can often be omitted from a class: System.out.println(post.toString()); Calls to println with just an object automatically result in toString being called: System.out.println(post); Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

26 Overriding toString in MessagePost
Objektorienterad programmering d2, förel. 10 Overriding toString in MessagePost public class MessagePost extends Post { ... public String toString() return super.toString() + "\n" + " message: " + message+ "\n"; } Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

27 Objektorienterad programmering d2, förel. 10
Protected access Private access in the superclass may be too restrictive for a subclass. The closer inheritance relationship is supported by protected access. Protected access is more restricted than public access. We still recommend keeping fields private. Define protected accessors and mutators. Klasser kan vara public, protected eller paketprivata (men ej privata) Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

28 Visibility of class members
Objektorienterad programmering d2, förel. 10 Visibility of class members Modifier In class In package In subclass World public Yes protected No no modifier (package private) Yes inside package No ow private Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

29 Objektorienterad programmering d2, förel. 10
Access levels SomeClass SubClass1 Client1 private somePackage someOtherPackage SubClass2 no modifier public protected Client2 Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

30 Objektorienterad programmering d2, förel. 10
Access levels Example A class member (method, constructor, variable) which is declared in SomeClass with access level private is only visible in SomeClass no modifier (package private) is visible in SomeClass, SubClass1, Client1 protected is visible in SomeClass, SubClass1, Client1, SubClass2 public is visible everywhere Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

31 Access levels and overriding
Objektorienterad programmering d2, förel. 10 Access levels and overriding An overriding method in a sub class must be at least as visible as the overridden method in its base class. Visibility in base class Allowed visibility in sub class public protected protected public package private Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

32 Overriding and Covariant Return Types
Objektorienterad programmering d2, förel. 10 Overriding and Covariant Return Types In Java, the return type of an overriding method is allowed to be a subtype of the return type of the overridden method. This is called covariance. The benefit is type safety Less need for unsafe type casts when calling overridden methods. Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

33 Overriding and Covariant Return Types
Objektorienterad programmering d2, förel. 10 Overriding and Covariant Return Types public class A {} public class B extends A {} public class Base { public A f() { return new A(); } public Base g() { return new Base(); } } public class Sub extends Base { public A f() { return new B(); } public B f() { return new B(); } // In particular, covariance can be // applied to the class itself: public Base g() { return new Base(); } public Base g() { return new Sub(); } public Sub g() { return new Sub(); } } Any of these is a correct overriding of f Any of these is a correct overriding of g Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

34 Overriding and Covariant Return Types
Objektorienterad programmering d2, förel. 10 Overriding and Covariant Return Types Example (no covariance) public class SomeClass implements Cloneable { public Object clone() { return super.clone(); } } ... SomeClass x = new SomeClass(); ... SomeClass y = (SomeClass)x.clone(); clone overrides Object.clone Without covariance we need an unsafe type cast here Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

35 Overriding and Covariant Return Types
Objektorienterad programmering d2, förel. 10 Overriding and Covariant Return Types Example (using covariance) public class SomeClass implements Cloneable { public SomeClass clone() { return (SomeClass)super.clone(); } } ... SomeClass x = new SomeClass(); ... SomeClass y = x.clone(); Overriding Object.clone using sub type as return type No need for type cast Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

36 The @Override annotation
Objektorienterad programmering d2, förel. 10 The @Override annotation A simple typing misstake can easily spoil overriding! Example public class Base { public void f() { ... } public void f(int x) { ... } public void g(float x) { ... } } public class Sub extends Base { public void f(int x) { ... } public void g(int x) { ... } } Ok, f overrides Base.f(int) Sub.g(int) does not override Base.g(float) - rather, it is a new method! Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

37 The @Override annotation
Objektorienterad programmering d2, förel. 10 The @Override annotation annotation indicates to the compiler that a method is intended to override some method in a super class. If a method is annotated but does not override a super class method, a compilation error results. Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

38 The @Override annotation
Objektorienterad programmering d2, förel. 10 The @Override annotation public class Base { public void f() { ... } public void f(int x) { ... } public void g(float x) { ... } } public class Sub extends Base { @Override public void f(int x) { ... } @Override public void g(int x) { ... } } Ok, f overrides Base.f(int) The compiler signals an error Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2

39 Objektorienterad programmering d2, förel. 10
Review The declared type of a variable is its static type. Compilers check static types. The type of the object a variable refers to is its dynamic type. Dynamic types are used at runtime. Methods may be overridden in a subclass. Method lookup starts with the dynamic type. Protected access supports inheritance. Overriding methods may have covariant return types. annotation makes overriding safer. Objektorienterad programmering, DAT050, DAI2, 17/18, lp 1 DAT050, 17/18, lp 2


Download ppt "10 More about inheritance"

Similar presentations


Ads by Google