+ All Categories
Home > Documents > Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages...

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

Date post: 31-Mar-2020
Category:
Upload: others
View: 10 times
Download: 0 times
Share this document with a friend
29
Inheritance Ric Glassey [email protected]
Transcript
Page 1: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

Inheritance

Ric Glassey [email protected]

Page 2: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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

Page 3: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

OBJECT-ORIENTED CONCEPTS

3

Page 4: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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

Page 5: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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

Page 6: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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

Page 7: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

Inheritance amongst species

7

Animal

Mammal

Dog Cat

Poodle Dalmation

Bird

Chicken Sparrow Eagle

Golden Eagle

Page 8: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

Polymorphism in peppered moths

8

Page 9: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

NEWSFEED APPLICATION

9

Page 10: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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  

Page 11: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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  

Page 12: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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();                  }            }  

Page 13: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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

Page 14: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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

Page 15: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

Superclass: Post

15

getTextgetTimeStamp

message

MessagePost

getImageFilegetCaption

filenamecaption

PhotoPost

likeunlikeaddCommentgetTimeStampdisplay

usernametimestamplikescomments

Post

Page 16: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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

Page 17: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

INHERITANCE IN JAVA

17

Page 18: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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...  }  

Page 19: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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

Page 20: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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()!  

Page 21: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

SUBTYPING AND SUBSTITUTION

21

Page 22: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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  

Page 23: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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

Page 24: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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);  

Page 25: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

POLYMORPHIC VARIABLES

25

Page 26: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

“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  

Page 27: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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

Page 28: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

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

Page 29: Inheritance - KTH · Object-Oriented Concepts • The family of object-oriented languages incorporate three main concepts: – Encapsulation • Package data and methods into a single

Readings

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

29


Recommended