lecture 12
TRANSCRIPT
![Page 1: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/1.jpg)
Lecture-12Instructor Name:
Object Oriented Programming
![Page 2: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/2.jpg)
Today’s Lecture
Inheritance
2
![Page 3: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/3.jpg)
Inheritance
Introduction While programming we may face problem of Code Duplication. Duplicate code is a computer programming term for a
sequence of source code that occurs more than once, either within a program or across different programs owned or maintained by the same entity.
Inheritance is a mechanism that provides us with a solution to our problem of duplication.
Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another.
With the use of inheritance the information is made manageable in a hierarchical order. 3
![Page 4: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/4.jpg)
Inheritance
Introduction Inheritance allows us to define one class as an extension of
another class. The class which inherits the properties of other is known as
subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class).
A superclass is a class that is extended by another class. A subclass is a class that extends (inherits from) another
class. It inherits all fields and methods from its superclass. The concept of inheritance is also known as re-usability or
extendable classes or sub classing or derivation. Classes that are linked through inheritance relationships form
an inheritance hierarchy.
4
![Page 5: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/5.jpg)
Inheritance
Why Use Inheritance? For Method Overriding (used for Runtime Polymorphism). It's main uses are to enable polymorphism and to be able to
reuse code for different classes by putting it in a common super class
For code Re-usability
5
![Page 6: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/6.jpg)
Inheritance
Advantage of Inheritance If we develop any application using concept of Inheritance,
that application have following advantages,
Application development time is less.
Application take less memory.
Application execution time is less.
Application performance is enhance (improved).
Redundancy (repetition) of the code is reduced or
minimized so that we get consistence results and less
storage cost. 6
![Page 7: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/7.jpg)
Inheritance
Important Points In java programming one derived class can extends only one
base class because java programming does not support multiple inheritance through the concept of classes, but it can be supported through the concept of Interface.
Whenever we develop any inheritance application first create an object of bottom most derived class but not for top most base class.
When we create an object of bottom most derived class, first we get the memory space for the data members of top most base class, and then we get the memory space for data member of other bottom most derived class.
Bottom most derived class contains logical appearance for the data members of all top most base classes.
If we do not want to give the features of base class to the derived class then the definition of the base class must be preceded by final hence final base classes are not reusable or not inheritable.
7
![Page 8: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/8.jpg)
Inheritance
Important Points If we are do not want to give some of the features of base
class to derived class than such features of base class must be as private hence private features of base class are not inheritable or accessible in derived class.
Data members and methods of a base class can be inherited into the derived class but constructors of base class can not be inherited because every constructor of a class is made for initializing its own data members but not made for initializing the data members of other classes.
An object of base class can contain details about features of same class but an object of base class never contains the details about special features of its derived class (this concept is known as scope of base class object).
For each and every class in java there exists an implicit predefined super class called java.lang.Object. because it providers garbage collection facilities to its sub classes for collecting un-used memory space and improved the performance of java application.
8
![Page 9: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/9.jpg)
Inheritance
Inheritance in Java - Syntaxpublic class Super-Name{
//methods and fields
}
public class Subclass-Name extends Superclass-Name {
//methods and fields
}
extends is the keyword used to inherit the properties of a class. Given above is the syntax of extends keyword 9
![Page 10: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/10.jpg)
Inheritance
Understanding Inheritance with Example
public class Calculation{
private int z;
public void addition(int x, int y){
z=x+y; System.out.println("The sum of the given
numbers:"+z); }
public void Substraction(int x,int y){
z=x-y; System.out.println("The difference between the given numbers:"+z);
}}
10
![Page 11: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/11.jpg)
Inheritance
Understanding Inheritance with Example
public class My_Calculation extends Calculation{
public void multiplication(int x, int y){
z=x*y; System.out.println("The product of the given
numbers:"+z); }
public static void main(String args[]){
int a=20, b=10; My_Calculation demo = new My_Calculation(); demo.addition(a, b); \\parent class methoddemo.Substraction(a, b); \\parent class methoddemo.multiplication(a, b); \\Child class method
} }
11
![Page 12: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/12.jpg)
Inheritance - Example
Accessing Members of Super Class
In the given program when an object to My_Calculation class is created, a copy of the contents of the super class is made with in it. That is why, using the object of the subclass you can access the members of a super class.
12
![Page 13: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/13.jpg)
Inheritance
The Super Keyword The super keyword is similar to this keyword following are the
scenarios where the super keyword is used. It is used to differentiate the members of superclass from
the members of subclass, if they have same names. It is used to invoke the superclass constructor from
subclass.Differentiating the members If a class is inheriting the properties of another class. And if
the members of the superclass have the names same as the sub class, to differentiate these variables we use super keyword as shown below.
super.variable;
super.method();13
![Page 14: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/14.jpg)
Inheritance
Invoking Superclass Constructor If a class is inheriting the properties of another class, the
subclass automatically acquires the default constructor of the super class. But if you want to call a parametrized constructor of the super class, you need to use the super keyword as shown below
super(values) We will see implementation of super key word in upcoming
slides.
14
![Page 15: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/15.jpg)
Inheritance - Example
The Social Network (Facebook) Example We will implement a prototype of social network like Facebook The prototype should at least include following functionality
It should allow us to create text and photo posts. Text posts consist of a message of arbitrary length,
possibly spanning multiple lines. Photo posts consist of an image and a caption. Some additional details are stored with each post.
It should store this information permanently so that it can be used later.
It should provide a search function that allows us to find, for example, all posts by a certain user or all photos within a given date range.
It should allow us to display lists of posts, such as a list of the most recent posts or a list of all posts by a given user.
It should allow us to remove information.
15
![Page 16: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/16.jpg)
Facebook Example
Message Post The details we want to store for each message post are:
the username of the author the text of the message a time stamp (time of posting) show many people like this post a list of comments on this post by other users
16
![Page 17: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/17.jpg)
Facebook Example
Photo Post The details we want to store for each photo post are:
the username of the author the filename of the image to display the caption for the photo (one line of text) a time stamp (time of posting) how many people like this post a list of comments on this post by other users
17
![Page 18: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/18.jpg)
Facebook Example
Classes & Objects for Network Project What classes to use for the project
MessagePost PhotoPost
What Data the object of this class will encapsulate
MessagePost MessagePostusername usernamemessage filenametimestamp captionlikes timestampcomments like
comments
18
![Page 19: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/19.jpg)
Facebook Example
Classes & Objects for Network Project
What may be the possible method for these classes?
![Page 20: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/20.jpg)
Facebook Example
Classes & Objects for Facebook Project Here is complete class that shows both data and behaviour
![Page 21: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/21.jpg)
Facebook Example – MessagePost Class
import java.util.ArrayList;
public class MessagePost { private String username; // username of the post's author private String message; // an arbitrarily long, multi-line message private long timestamp; private int likes; private ArrayList<String> comments;
public MessagePost(String author, String text) { username = author; message = text; timestamp = System.currentTimeMillis(); likes = 0; comments = new ArrayList<String>(); }
![Page 22: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/22.jpg)
Facebook Example – MessagePost Class
public void like() { likes++; } public void unlike() { if (likes > 0) { likes--; } }
public void addComment(String text) { comments.add(text); }
![Page 23: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/23.jpg)
Facebook Example – MessagePost Class
public String getText() { return message; } public long getTimeStamp() { return timestamp; } private String timeString(long time){ long current = System.currentTimeMillis(); long pastMillis = current - time; long seconds = pastMillis/1000; long minutes = seconds/60; if(minutes > 0) { return minutes + " minutes ago"; } else { return seconds + " seconds ago"; } }
![Page 24: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/24.jpg)
Facebook Example – MessagePost Class
public void display(){ System.out.println(username); System.out.println(message); System.out.print(timeString(timestamp)); if(likes > 0) { System.out.println(" - " + likes + " people like this."); } else { System.out.println(); } if(comments.isEmpty()) { System.out.println(" No comments."); } else { System.out.println(" " + comments.size() + " comment(s). Click here to view."); } }}
![Page 25: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/25.jpg)
Facebook Example – PhotoPost Classimport java.util.ArrayList;public class PhotoPost { private String username; // username of the post's author private String filename; // the name of the image file private String caption; // a one line image caption private long timestamp; private int likes; private ArrayList<String> comments;
public PhotoPost(String author, String filename, String caption) { username = author; this.filename = filename; this.caption = caption; timestamp = System.currentTimeMillis(); likes = 0; comments = new ArrayList<String>(); }
![Page 26: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/26.jpg)
Facebook Example – PhotoPost Class public void like() { likes++; } public void unlike() { if (likes > 0) { likes--; } } public void addComment(String text) { comments.add(text); }
![Page 27: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/27.jpg)
Facebook Example – PhotoPost Class public String getImageFile() { return filename; }
public String getCaption() { return caption; }
public long getTimeStamp() { return timestamp; }
![Page 28: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/28.jpg)
Facebook Example – PhotoPost Class public void display(){ System.out.println(username); System.out.println(" [" + filename + "]"); System.out.println(" " + caption); System.out.print(timeString(timestamp)); if(likes > 0) { System.out.println(" - " + likes + " people like this."); } else { System.out.println(); } if(comments.isEmpty()) { System.out.println(" No comments."); } else { System.out.println(" " + comments.size() + " comment(s). Click here to view."); } }
![Page 29: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/29.jpg)
Facebook Example – PhotoPost Class private String timeString(long time) { long current = System.currentTimeMillis(); long pastMillis = current - time; long seconds = pastMillis/1000; long minutes = seconds/60; if(minutes > 0) { return minutes + " minutes ago"; } else { return seconds + " seconds ago"; } }}
![Page 30: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/30.jpg)
Facebook Example
NewsFeed Class Once we have defined the MessagePost and PhotoPost
classes, we can create as many post objects as we need—one object per message post or photo post that we want to store.
We also need another object: an object representing the complete news feed that can hold a collection of message posts and a collection of photo posts.
For this, we shall create a class called NewsFeed. The NewsFeed object could itself hold two collection
objects (for example, of types ArrayList <MessagePost> and ArrayList<PhotoPost>).
![Page 31: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/31.jpg)
Facebook Example – NewsFeed Class import java.util.ArrayList;public class NewsFeed{ private ArrayList<MessagePost> messages; private ArrayList<PhotoPost> photos;
public NewsFeed() { messages = new ArrayList<MessagePost>(); photos = new ArrayList<PhotoPost>(); } public void addMessagePost(MessagePost message) { messages.add(message); } public void addPhotoPost(PhotoPost photo) { photos.add(photo); }
/** * Show the news feed. Currently: print the news feed
details * to the terminal. (To do: replace this later with
display * in web browser.) */ public void show() { // display all text posts for(MessagePost message : messages) { message.display(); System.out.println(); // empty line between
posts }
// display all photos for(PhotoPost photo : photos) { photo.display(); System.out.println(); // empty line between
posts } }}
![Page 32: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/32.jpg)
Facebook Example – NewsFeed Class public void show() { // display all text posts for(MessagePost message : messages) { message.display(); System.out.println(); // empty line between posts }
// display all photos for(PhotoPost photo : photos) { photo.display(); System.out.println(); // empty line between posts } }}
![Page 33: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/33.jpg)
Facebook Example
Objects in Facebook Example
![Page 34: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/34.jpg)
Facebook Example
Problem in Facebook Example Application still have many problem and the most obvious
one is code duplication The two classes defined are very much similar and majority of
classes’ code is identical with only a few differences. A single change need to be implemented in both classes
which is annoying. In addition, associated with maintenance of code duplication
is always the danger of introducing errors, because the maintenance programmer might not realize that an identical change is needed at a second (or third) location
There is another spot where we have code duplication: in the NewsFeed class. We can see that everything in that class is done twice—once for message posts and once for photo posts.
The class defines two list variables, then creates two list objects, defines two add methods, and has two almost-identical blocks of code in the show method to print out the lists.
![Page 35: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/35.jpg)
Facebook Example
Problem in Facebook Example What will happened if we want to add new type of post
We need to write code again
We need to do the same for the fourth type of post and so on.
Solution to Problem?Inheritance
![Page 36: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/36.jpg)
Using Inheritance
Inheritance to Avoid Code Duplication
Inheritance is a mechanism that provides us with a solution to our problem of duplication.
The idea is simple: instead of defining the MessagePost and PhotoPost classes completely independently, we first define a class that contains everything these two have in common.
Both MessagePost and PhotoPost is a post.
We define a new class and call this class as Post.
By defining new class Post we need to define the common feature only once.
![Page 37: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/37.jpg)
Using Inheritance
New Structure of Facebook Example
![Page 38: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/38.jpg)
Using Inheritance
New Structure of Facebook Example We say that the class MessagePost inherits from class Post.
Class PhotoPost also inherits from Post Class Post(the class that the others inherit from) is called the
parent class or superclass. The inheriting classes (MessagePost and PhotoPost in this
example) are referred to as child classes or subclasses Inheritance is sometimes also called as is-a relationship The reason is that a subclass is a specialization of a
superclass. We can say that “a message post is a post” and “a photo post is a post.”
Instances of class MessagePost will have all fields and methods defined in class MessagePost and in class Post and Instances of PhotoPost will have all fields and methods defined in PhotoPost and in Post
![Page 39: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/39.jpg)
Using Inheritance – Facebook Example
Class Postimport java.util.ArrayList;
public class Post { private String username; // username of the post's
author private long timestamp; private int likes; private ArrayList<String> comments;
public Post(String author) { username = author; timestamp = System.currentTimeMillis(); likes = 0; comments = new ArrayList<String>(); }
![Page 40: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/40.jpg)
Using Inheritance – Facebook Example
Class Post public void like() { likes++; }
public void unlike() { if (likes > 0) { likes--; } }
public void addComment(String text) { comments.add(text); }
![Page 41: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/41.jpg)
Using Inheritance – Facebook Example
Class Post public long getTimeStamp() { return timestamp; } private String timeString(long time) { long current = System.currentTimeMillis(); long pastMillis = current - time; long seconds = pastMillis/1000; long minutes = seconds/60; if(minutes > 0) { return minutes + " minutes ago"; } else { return seconds + " seconds ago"; } }
![Page 42: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/42.jpg)
Using Inheritance – Facebook Example
Class Post public void display(){ System.out.println(username); System.out.print(timeString(timestamp)); if(likes > 0) { System.out.println(" - " + likes + " people like
this."); } else { System.out.println(); } if(comments.isEmpty()) { System.out.println(" No comments."); } else { System.out.println(" " + comments.size() + "
comment(s). Click here to view."); } } }
![Page 43: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/43.jpg)
Using Inheritance – Facebook Example
Class MessagePostimport java.util.ArrayList;public class MessagePost extends Post{ private String message; public MessagePost(String author, String text) { super(author); message = text; } public String getText() { return message; } public String toString(){ super.toString(); return "My Text"; }}
![Page 44: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/44.jpg)
Using Inheritance – Facebook Example
Class MessagePost & Super Call Notice the super() call in MessagePost Class
The keyword super is a call from the subclass constructor to the constructor of the superclass.
Its effect is that the Post constructor is executed as part of the MessagePost constructor’s execution.
When we create a message post, the MessagePost constructor is called, which, in turn, as its first statement, calls the Post constructor.
The Post constructor initializes the post’s fields, and then returns to the MessagePost constructor, which initializes the remaining field defined in the MessagePost class.
![Page 45: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/45.jpg)
Using Inheritance – Facebook Example
Class MessagePost & Super Call For this to work, those parameters needed for the
initialization of the post fields are passed on to the superclass constructor as parameters to the super call.
The constructor of a subclass must always invoke the constructor of its superclass as its first statement. If the source code does not include such a call, Java will attempt to insert a call automatically, , to ensure that the superclass fields get properly initialized.
The inserted call is equivalent to writing
super();
Inserting this call automatically works only if the superclass has a constructor without parameters (because the compiler cannot guess what parameter values should be passed). Otherwise, an error will be reported
![Page 46: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/46.jpg)
Using Inheritance – Facebook Example
Class PhotoPostimport java.util.ArrayList;
public class PhotoPost extends Post{ private String filename; // the name of the image file private String caption; // a one line image caption
public PhotoPost(String author, String filename, String caption)
{ super(author); this.filename = filename; this.caption = caption; }
![Page 47: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/47.jpg)
Using Inheritance – Facebook Example
Class PhotoPost public String getImageFile() { return filename; } public String getCaption() { return caption; }}
![Page 48: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/48.jpg)
Using Inheritance – Facebook Example
Adding other Posts Inheritance Hierarchy is set up and now we can easily add
new Post type to Facebook
Suppose we want to add new Post EventPost class
Here the concept of reuseablity works
We can reuse the code that we have written for photo posts and message posts (in the Post class) so that it also works for the EventPost class.
![Page 49: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/49.jpg)
Using Inheritance – Facebook Example
Adding other Posts
![Page 50: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/50.jpg)
Using Inheritance – Facebook Example
What happened if requirement change?
Imagine change in requirements : event posts in our Facebook application will not have a “Like” button or comments attached. They are for information only.
How do we achieve this? EventPost is a subclass of Post, it automatically inherits the
likes and comments fields. Is this a problem? We could leave everything as it is and decide to never display
the likes count or comments for event posts—just ignore the fields.
This does not feel right. Having the fields present but unused invites problems. Someday a maintenance programmer will come along who does not realize that these fields should not be used and try to process them.
OR We could write EventPost without inheriting from Post. But
then we are back to code duplication for the username and timestamp fields and their methods
![Page 51: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/51.jpg)
Using Inheritance – Facebook Example
Solution to Change in Requrement The solution is to refactor the class hierarchy. We can introduce a new superclass for all posts that have
comments attached (named CommentedPost), which is a subclass of Post
We then shift the likes and comments fields from the Post class to this new class.
MessagePost and PhotoPost are now subclasses of our new CommentedPost class. MessagePost objects inherit everything from both superclasses and have the same fields and methods as before
EventPost inherits from Post directly. Objects of class EventPost will inherit the username and timestamp, but not the comments
![Page 52: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/52.jpg)
Using Inheritance – Facebook Example
Solution to Change in Requrement
![Page 53: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/53.jpg)
Inheritance
Class NewsFeedImport java.util.ArrayList;
public class NewsFeed{ private ArrayList<Post> posts;
public NewsFeed() { posts = new ArrayList<Post>(); }
public void addPost(Post post) { posts.add(post); }
![Page 54: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/54.jpg)
Inheritance
Class NewsFeed public void show() { // display all posts for(Post post : posts) { post.display(); System.out.println(); } }}
In this class we have one add method to add both message
and photo posts
We have one show method to show both message and photo
posts
![Page 55: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/55.jpg)
Inheritance
Summarizing Inheritance Advantages
Recall the Inheritance advantages with Facebook
example
Avoid Code Duplication
Code Reuse
Easier maintenance
Extendibility
![Page 56: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/56.jpg)
Subtyping
What is Subtyping? Subtyping refers to compatibility of interfaces. A type B is a subtype of A if every function that can be
invoked on an object of type A can also be invoked on an object of type B.
To implement a subtype, it is often useful to use the implementation of its supertype This is also called “subclassing”
In Java:class B extends A
B is a subtype of AB inherits from A
class C implements FC is a subtype of F
both subtyping and inheritance
just subtyping
![Page 57: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/57.jpg)
Subtyping
Method Dispatch B is a subtype of A
If both A and B have a method display which method should
be called?A a = new A ();B b = new B ();
a.display ();b.display ();a = b;a.display ()
Calls class A’s display methodCalls class B’s display method
Calls class B’s display method
![Page 58: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/58.jpg)
Subtyping
Subclasses & Subtypes in Facebook Example
The type of an object that was created from class MessagePost is MessagePost.
We also discussed that classes may have subclasses. Thus, the types defined by the classes can have subtypes. In our example, the type MessagePost is a subtype of type
Post. What else is subtype of type Post?
![Page 59: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/59.jpg)
Subtyping
Subtyping and Assignment Consider the following declaration
Car car=new Car() Above is a valid assignment, because an object of type Car is
assigned to a variable declared to hold objects of type Car a variable can hold objects of its declared type or of any
subtype of its declared type. Imagine that we have a class Vehicle with two subclasses, Car
and Bicycle In this case, the typing rule admits that the following
assignments are all legal:Vehicle v1 = new Vehicle();Vehicle v2 = new Car();Vehicle v3 = new Bicycle();
![Page 60: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/60.jpg)
Subtyping
Subtyping and Assignment Declaring a variable of type Vehicle states that this variable
can hold vehicles. A car is a vehicle, it is perfectly legal to store a car in a
variable that is intended for vehicles. This principle is known as substitution. In object-oriented languages, we can substitute a subclass
object where a superclass object is expected, because the subclass object is a special case of the superclass.
Illegal DeclarationsCar c1 = new Vehicle(); // this is an error!Car c2 = new Bicycle(); // this is an error!
![Page 61: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/61.jpg)
Subtyping
Subtyping and Parameter Passing Passing a parameter (that is, assigning an actual parameter
to a formal parameter variable) behaves in exactly the same way as an assignment to a variable.
This is why we can pass an object of type MessagePost to a method that has a parameter of type Post.
We have the following definition of the addPost method in class NewsFeed:
public class NewsFeed
{
public void addPost(Post post){
. . .
}
}
![Page 62: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/62.jpg)
Subtyping
Subtyping and Parameter Passing We can now use this method to add message posts and photo
posts to the feed:NewsFeed feed = new NewsFeed();
MessagePostmessage = new MessagePost(. . .);
PhotoPost photo = new PhotoPost(. . .);
feed.addPost(message);
feed.addPost(photo); Because of subtyping rules, we need only one method (with a
parameter of type Post) to add both MessagePost and PhotoPost objects.
![Page 63: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/63.jpg)
Polymorphic Variable
Polymorphic Variable in Facebook example
Variables holding object types in Java are polymorphic variable
The use of a polymorphic variable helps us simplify our show method.
The body of this method isfor(Post post : posts) {
post.display();System.out.println();
}
The actual posts that we get out of the list are of type MessagePost or PhotoPost, not of type Post.
We use a loop variable of type Post, because variables are polymorphic.
The post variable is able to hold MessagePost and PhotoPost objects, because these are subtypes of Post.
![Page 64: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/64.jpg)
Casting
Type Loss & Casting Sometimes the rule that we cannot assign from a supertype
to a subtype is more restrictive than necessary. If we know that the supertype variable holds a subtype
object, the assignment could actually be allowed. For example:
Vehicle v;
Car c = new Car();
v = c; // correct
c = v; // error The above statements would not compile: we get a compiler
error in the last line, because assigning a Vehicle variable to a Car variable (supertype to subtype) is not allowed.
![Page 65: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/65.jpg)
Casting
Type Loss & Casting However, if we execute these statements in sequence, we
know that we could actually allow this assignment. We can see that the variable v actually contains an object of
type Car, so the assignment to c would be okay. The compiler is not that smart. It translates the code line by
line, so it looks at the last line in isolation without knowing what is currently stored in variable v.
This is called type loss. The type of the object in v is actually Car, but the compiler does not know this.
Solution to this problem is by explicitly telling the type system that the variable v holds a Car object. We do this using a cast operator:
c = (Car) v; // okay
![Page 66: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/66.jpg)
Casting
Type Loss & Casting Now consider this code fragment, in which Bicycle is also a
subclass of Vehicle: Find which line will give errorVehicle v;Car c;Bicycle b;c = new Car();v = c; b = (Bicycle) c; b = (Bicycle) v;
Out of last two First will give compile time error and second statement will give runtime error
Casting should be avoided wherever possible, because it can lead to runtime errors
![Page 67: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/67.jpg)
Autoboxing & Wrapper Classes
Creating Collection of primitive types An ArrayList supports only non primitive data types. But if we want to creatre list of primitive data types line
int,boolean. What can we do? Java’s solution to this problem is wrapper classes. Every
primitive type in Java has a corresponding wrapper class that represents the same type but is a real object type.
The wrapper class for int, for example, is called Integer. The following statement explicitly wraps the value of the
primitive intvariable ix in an Integer object:Integer iwrap = new Integer(ix);
And now iwrap could obviously easily be stored in ArrayList<Integer> collection, for instance.
![Page 68: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/68.jpg)
Autoboxing & Wrapper Classes
Creating Collection of primitive types However, storing of primitive values into an object collection
is made even easier through a compiler feature known as autoboxing.
Autoboxing is performed automatically when a primitive-type value is used in a context requiring a wrapper type.
Whenever a value of a primitive type is used in a context that requires a wrapper type, the compiler automatically wraps the primitive-type value in an appropriate wrapper object.
This means that primitive-type values can be added directly to a collection:private ArrayList<Integer> markList;...public void storeMarkInList(int mark){markList.add(mark);}
The reverse operation—unboxing—is also performed automatically
![Page 69: Lecture 12](https://reader034.vdocuments.us/reader034/viewer/2022051520/58f0eb821a28abbd138b460d/html5/thumbnails/69.jpg)
69