Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages...

Post on 31-Mar-2020

10 views 0 download

transcript

Inheritance

Ric Glassey glassey@kth.se

Outline

•  Inheritance –  Aim: Improve object-oriented program design –  Concepts

•  Inheritance •  Subtyping •  Substitution •  Polymorphic variables

–  Issues addressed by inheritance: •  Code duplication •  Developer effort •  Code maintenance •  Extensibility

–  Illustrative design example: NewsFeed

2

OBJECT-ORIENTED CONCEPTS

3

Programming Paradigms

•  Multiple programming paradigms exist that influence the design of languages: –  Imperative: how to solve a problem in explicit steps

•  e.g. Machine Code –  Structured: introduce structural elements

(procedures, blocks, looping constructs, etc) •  e.g. C

–  Declarative: describes what the desired solution is •  e.g. Haskell

•  Object-oriented generally blends imperative and structured, with the philosophy that everything* should be modelled as an object

4

Object-Oriented Concepts

•  The family of object-oriented languages incorporate three main concepts: –  Encapsulation

•  Package data and methods into a single component •  Promote information hiding (prevent direct access to object

state) –  Inheritance

•  One subclass can extend from another superclass •  Subclass can inherit data and methods of the superclass •  Subclass can override data and methods of the superclass •  Subclass can introduce additional data and methods

–  Polymorphism •  Classes that are related (by interface or inheritance) can be

used interchangeably within certain constraints

5

Encapsulation

•  Class specifies the data and methods •  Objects are instances of classes

6

addMessagePostaddPhotoPostshowPosts

messagesphotos

NewsFeedClass  name  

Class  fields  

Class  methods  

Instance  of  class  (object)  

: NewsFeed

messages

photos

Inheritance amongst species

7

Animal

Mammal

Dog Cat

Poodle Dalmation

Bird

Chicken Sparrow Eagle

Golden Eagle

Polymorphism in peppered moths

8

NEWSFEED APPLICATION

9

Initial Object-Oriented Design

•  Design a ‘facebook’ like application, with requirements: –  supports posting and display of messages and photos –  users can also like, unlike and comment on posts

•  A good starting point is to model entities as classes:

10

likeunlikeaddCommentgetTextgetTimeStampdisplay

usernamemessagetimestamplikescomments

MessagePost

addMessagePostaddPhotoPostshowPosts

messagesphotos

NewsFeed

likeunlikeaddCommentgetImageFilegetCaptiongetTimeStampdisplay

usernamefilenamecaptiontimestamplikescomments

PhotoPost

See  Chp  8,  “Objects  First  with  Java”  5th  ed.  for  full  source  code  

Viewed as a network of instantiated objects

11

: NewsFeed

messages

photos

: MessagePost : MessagePost : MessagePost

: PhotoPost: PhotoPost : PhotoPost : PhotoPost

: ArrayList<MessagePost>

: ArrayList<PhotoPost>

See  Chp  8,  “Objects  First  with  Java”  5th  ed.  for  full  source  code  

Two Clear Problems

1.  Code duplication in Posts 2.  Additional Effort in NewsFeed to handle two

arrays in an identical manner

12

likeunlikeaddCommentgetTextgetTimeStampdisplay

usernamemessagetimestamplikescomments

MessagePost

likeunlikeaddCommentgetImageFilegetCaptiongetTimeStampdisplay

usernamefilenamecaptiontimestamplikescomments

PhotoPost

         public  void  showPosts()  {                  //  display  all  test  posts                  for(MessagePost  message  :  messages)  {                          message.display();                  }                    //  display  all  test  posts                  for(PhotoPost  photo  :  photos)  {                          photo.display();                  }            }  

Implications

•  If we decide to make a change (e.g. introduce a Comment object in place of a String for all posts), we have twice as much work

•  Worse still, if multiple developers are involved, they may not be aware that changes are required in multiple locations

•  If we decide we really need a VideoPost to extend functionality, we have a lot of repetition and effort required to integrate

•  This code becomes a maintenance nightmare –  and this is only a three class application

13

Inheritance as a solution

•  Both problems (duplication & effort) can be addressed using inheritance

•  Inheritance lets us: –  Find all that is common between classes

•  data •  methods

–  Create a new Superclass –  Allow a Subclass to inherit from this superclass (forming

an “is a” relationship) –  Allow subclasses to also specify differences from the

Superclass –  Treat Subclasses as if they were of the superclass type*

14

Superclass: Post

15

getTextgetTimeStamp

message

MessagePost

getImageFilegetCaption

filenamecaption

PhotoPost

likeunlikeaddCommentgetTimeStampdisplay

usernametimestamplikescomments

Post

Implications of inheritance

•  If we decide to make a fundamental change to post behaviour, we only need to change the Post class, and all classes will adopt the change

•  We are reusing code more effectively •  Less effort to write code, and less chance of

making a mistake via copying code •  Improved application semantics: –  Before, there was no connection between

MessagePost and PhotoPost (implicit organisation via naming convention)

–  After, there is now explicit organisation and documented relationship between all posts

16

INHERITANCE IN JAVA

17

Using the ‘extends’ keyword

18

public  class  Post  {            private  String  username;          private  long  timestamp;          private  int  likes;          private  ArrayList<String>  comments;          //  remaining  code  omitted...  }    public  class  MessagePost  extends  Post  {                    private  String  message;          //  remaining  code  omitted...  }    public  class  PhotoPost  extends  Post  {                    private  String  filename;          private  String  caption;          //  remaining  code  omitted...  }  

Access rights between classes

•  To preserve information hiding, subclasses cannot directly access private fields of a superclass

•  Depending upon our design intent, we can declare fields as being: –  public: accessible from any class –  private: inaccessible to all classes –  protected: accessible within inheritance hierarchy

19

Initialisation with inheritance using super( )

•  Constructing objects within an inheritance hierarchy requires some attention, as we use constructors from multiple classes: –  The subclass

constructor method

–  Any superclass constructor method

20

public  class  Post  {            public  Post(String  author)  {                  username  =  author;                  timestamp  =  System.currentTimeMillis();                  likes  =  0;                  comments  =  new  ArrayList<String>;          }          //  remaining  code  omitted...  }    public  class  MessagePost  extends  Post  {                    public  MessagePost(String  author,  String  text)  {                  super(author);                  message  =  text;          }          //  remaining  code  omitted...  }  

n.b.  super(x,y)  must  come  first  or    the  compiler  will  assume  super()!  

SUBTYPING AND SUBSTITUTION

21

Updated NewsFeed design

22

: NewsFeed

posts

: MessagePost : PhotoPost : MessagePost

: ArrayList<Post>

addPostshowPosts

posts

NewsFeed

The  applicaIon  design  is  much  simplified  because  we  do  not  have  to  handle  both  classes  of  post  separately.    The  observaIon  here  is  that  we  can  use  the    fact  that  a  subclass  of  a  superclass  is  a  also  a  subtype  of  that  class.  Thus,  the  subtypes  MessagePost  and  PhotoPost  can  be  treated  as  types  of  Post  

Valid Subtype assignment

23

//  object  and  variables  types  must  match  when  making  an  assignment  Car  c  =  new  Car(  );    //  also  legal,  as  Car  and  Bicycle  are  subtypes  of  Vehicle  Vehicle  v1  =  new  Vehicle();  Vehicle  v2  =  new  Car();  Vehicle  v3  =  new  Bicycle();    //  however  these  are  illegal!  >>  think  why?  Car  c1  =  new  Vehicle();  Car  c2  =  new  Bicycle();  

Vehicle

Car

Bicycle

Subtyping within NewsFeed

24

public  class  NewsFeed  {            private  ArrayList<Post>  posts;            public  NewsFeed()  {                  posts  =  new  ArrayList<Post>();          }                    public  void  addPost(Post  post)  {                  posts.add(post);          }  }      NewsFeed  feed  =  new  NewsFeed();  MessagePost  message  =  new  MessagePost();  PhotoPost  photo  =  new  PhotoPost();    feed.addPost(message);  feed.addPost(photo);  

POLYMORPHIC VARIABLES

25

“Taking many shapes”

•  Java variables are polymorphic •  They can hold variables of different types*

–  Specifically, the declared type, or subtype of the declared type

•  Sometimes, we may need to be more specific and use

casting to return a subtype to its type:

26

for  (Post  post  :  posts)  {          //  does  not  matter  if  the  post  type  is  MessagePost    

 //  or  PhotoPost  as  they  are  subtypes  of  Post  and      //  have  the  same  interface  

       post.display();  }  

Vehicle  v;  Car  c  =  new  Car();  v  =  c;  //  type  switched  to  Vehicle  c  =  (Car)  v;  //  type  returned  to  Car  

Benefits of inheritance

•  Avoids code duplication •  Promotes code reuse •  Easier maintenance •  Improved extendibility •  Better semantics / documentation

•  A more sophisticated way to think in terms of object-oriented design of systems

27

Feedback!

•  Let me know your thoughts –  New to KTH / Sweden –  Help me gauge your expectations –  Help me understand your reactions

•  Each lecture will have a very fast questionnaire –  I promise to look at the data :-) –  Link here (or http://bit.ly/1ADRsOC ) –  And also on the course pages

28

Readings

•  Chp 8, “Objects First with Java” 5th ed.

29