SlideShare a Scribd company logo
Lecture-12
Instructor Name:
Object Oriented Programming
Today’s Lecture
 Inheritance
2
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
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
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
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
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
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
Inheritance
Inheritance in Java - Syntax
public 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
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
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 method
demo.Substraction(a, b); parent class method
demo.multiplication(a, b); Child class method
}
} 11
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
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
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
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
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
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
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 MessagePost
username username
message filename
timestamp caption
likes timestamp
comments like
comments 18
Facebook Example
Classes & Objects for Network Project
What may be the possible method for these classes?
Facebook Example
Classes & Objects for Facebook Project
 Here is complete class that shows both data and behaviour
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>();
}
Facebook Example – MessagePost Class
public void like()
{
likes++;
}
public void unlike()
{
if (likes > 0)
{
likes--;
}
}
public void addComment(String text)
{
comments.add(text);
}
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";
}
}
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.");
}
}
}
Facebook Example – PhotoPost Class
import 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>();
}
Facebook Example – PhotoPost Class
public void like()
{
likes++;
}
public void unlike()
{
if (likes > 0)
{
likes--;
}
}
public void addComment(String text)
{
comments.add(text);
}
Facebook Example – PhotoPost Class
public String getImageFile()
{
return filename;
}
public String getCaption()
{
return caption;
}
public long getTimeStamp()
{
return timestamp;
}
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.");
}
}
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";
}
}
}
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>).
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);
}
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
}
}
}
Facebook Example
Objects in Facebook Example
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.
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
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.
Using Inheritance
New Structure of Facebook Example
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
Using Inheritance – Facebook Example
Class Post
import 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>();
}
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);
}
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";
}
}
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.");
}
Using Inheritance – Facebook Example
Class MessagePost
import 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";
}
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.
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
Using Inheritance – Facebook Example
Class PhotoPost
import 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;
}
Using Inheritance – Facebook Example
Class PhotoPost
public String getImageFile()
{
return filename;
}
public String getCaption()
{
return caption;
}
}
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.
Using Inheritance – Facebook Example
Adding other Posts
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
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
Using Inheritance – Facebook Example
Solution to Change in Requrement
Inheritance
Class NewsFeed
Import java.util.ArrayList;
public class NewsFeed
{
private ArrayList<Post> posts;
public NewsFeed()
{
posts = new ArrayList<Post>();
}
public void addPost(Post post)
{
posts.add(post);
}
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
Inheritance
Summarizing Inheritance Advantages
 Recall the Inheritance advantages with Facebook example
 Avoid Code Duplication
 Code Reuse
 Easier maintenance
 Extendibility
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 A
B inherits from A
class C implements F
C is a subtype of F
both subtyping and inheritance
just subtyping
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 method
Calls class B’s display method
Calls class B’s display method
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?
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();
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 Declarations
Car c1 = new Vehicle(); // this is an error!
Car c2 = new Bicycle(); // this is an error!
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){
. . .
}
}
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.
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 is
for(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.
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.
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
Casting
Type Loss & Casting
 Now consider this code fragment, in which Bicycle is also a subclass of
Vehicle: Find which line will give error
Vehicle 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
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.
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
69

More Related Content

What's hot

java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
Shashwat Shriparv
 
inheritance
inheritanceinheritance
inheritance
Mohit Patodia
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
HoneyChintal
 
Inheritance in java
Inheritance in javaInheritance in java
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
dheeraj_cse
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
madhavi patil
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
G C Reddy Technologies
 
Interface
InterfaceInterface
Interface
kamal kotecha
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
Uzair Salman
 
Top 20 c# interview Question and answers
Top 20 c# interview Question and answersTop 20 c# interview Question and answers
Top 20 c# interview Question and answers
w3asp dotnet
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
Sherihan Anver
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
Gradeup
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10Terry Yoast
 
C# interview
C# interviewC# interview
C# interview
Thomson Reuters
 

What's hot (20)

java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
C# interview quesions
C# interview quesionsC# interview quesions
C# interview quesions
 
inheritance
inheritanceinheritance
inheritance
 
Unit 3 Java
Unit 3 JavaUnit 3 Java
Unit 3 Java
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
 
Inheritance in java
Inheritance in javaInheritance in java
Inheritance in java
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Unit 4 Java
Unit 4 JavaUnit 4 Java
Unit 4 Java
 
Dacj 2-1 a
Dacj 2-1 aDacj 2-1 a
Dacj 2-1 a
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Interface
InterfaceInterface
Interface
 
Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes Object Oriented Programming using JAVA Notes
Object Oriented Programming using JAVA Notes
 
Top 20 c# interview Question and answers
Top 20 c# interview Question and answersTop 20 c# interview Question and answers
Top 20 c# interview Question and answers
 
Java interview questions 2
Java interview questions 2Java interview questions 2
Java interview questions 2
 
20 most important java programming interview questions
20 most important java programming interview questions20 most important java programming interview questions
20 most important java programming interview questions
 
Core java questions
Core java questionsCore java questions
Core java questions
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
C# interview
C# interviewC# interview
C# interview
 
Chap11
Chap11Chap11
Chap11
 

Similar to Lecture 12

Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented concepts
Maryo Manjaruni
 
Learn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & InheritanceLearn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & Inheritance
Eng Teong Cheah
 
Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
SadiqullahGhani1
 
Inheritance in OOPs with java
Inheritance in OOPs with javaInheritance in OOPs with java
Inheritance in OOPs with java
AAKANKSHA JAIN
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
JayMistry91473
 
Php oop (1)
Php oop (1)Php oop (1)
Php oop (1)
Sudip Simkhada
 
Java OOPS Concept
Java OOPS ConceptJava OOPS Concept
Java OOPS Concept
Richa Gupta
 
concept of oops
concept of oopsconcept of oops
concept of oops
prince sharma
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
RudranilDas11
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
Inocentshuja Ahmad
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
Ajay Chimmani
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptx
kristinatemen
 
Inheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptxInheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptx
naeemcse
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
Ravi Bhadauria
 
Class properties
Class propertiesClass properties
Class properties
Siva Priya
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
ilias ahmed
 
oops-123991513147-phpapp02.pdf
oops-123991513147-phpapp02.pdfoops-123991513147-phpapp02.pdf
oops-123991513147-phpapp02.pdf
ArpitaJana28
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptx
mrxyz19
 

Similar to Lecture 12 (20)

Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented concepts
 
Learn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & InheritanceLearn C# Programming - Classes & Inheritance
Learn C# Programming - Classes & Inheritance
 
Oops
OopsOops
Oops
 
Opp concept in c++
Opp concept in c++Opp concept in c++
Opp concept in c++
 
Inheritance in OOPs with java
Inheritance in OOPs with javaInheritance in OOPs with java
Inheritance in OOPs with java
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
 
Php oop (1)
Php oop (1)Php oop (1)
Php oop (1)
 
Java OOPS Concept
Java OOPS ConceptJava OOPS Concept
Java OOPS Concept
 
concept of oops
concept of oopsconcept of oops
concept of oops
 
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptxSodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
SodaPDF-converted-inheritanceinjava-120903114217-phpapp02-converted.pptx
 
Question and answer Programming
Question and answer ProgrammingQuestion and answer Programming
Question and answer Programming
 
4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT4 pillars of OOPS CONCEPT
4 pillars of OOPS CONCEPT
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptx
 
Inheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptxInheritance in Java beginner to advance with examples.pptx
Inheritance in Java beginner to advance with examples.pptx
 
Object oreinted php | OOPs
Object oreinted php | OOPsObject oreinted php | OOPs
Object oreinted php | OOPs
 
Class properties
Class propertiesClass properties
Class properties
 
My c++
My c++My c++
My c++
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
oops-123991513147-phpapp02.pdf
oops-123991513147-phpapp02.pdfoops-123991513147-phpapp02.pdf
oops-123991513147-phpapp02.pdf
 
OOP in Java Presentation.pptx
OOP in Java Presentation.pptxOOP in Java Presentation.pptx
OOP in Java Presentation.pptx
 

More from talha ijaz

Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
talha ijaz
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
talha ijaz
 
Lecture 20-21
Lecture 20-21Lecture 20-21
Lecture 20-21
talha ijaz
 
Lecture 19
Lecture 19Lecture 19
Lecture 19
talha ijaz
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
talha ijaz
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
talha ijaz
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
talha ijaz
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
talha ijaz
 
Visual perception
Visual perceptionVisual perception
Visual perception
talha ijaz
 
Lecture 11
Lecture 11Lecture 11
Lecture 11
talha ijaz
 
Introduction
IntroductionIntroduction
Introduction
talha ijaz
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
talha ijaz
 

More from talha ijaz (15)

Lecture 23-24.pptx
Lecture 23-24.pptxLecture 23-24.pptx
Lecture 23-24.pptx
 
Lecture 22
Lecture 22Lecture 22
Lecture 22
 
Lecture 20-21
Lecture 20-21Lecture 20-21
Lecture 20-21
 
Lecture 19
Lecture 19Lecture 19
Lecture 19
 
Lecture 18
Lecture 18Lecture 18
Lecture 18
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
Visual perception
Visual perceptionVisual perception
Visual perception
 
Lecture 11
Lecture 11Lecture 11
Lecture 11
 
Introduction
IntroductionIntroduction
Introduction
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
Lecture 3
Lecture 3Lecture 3
Lecture 3
 
Lecture 2
Lecture 2Lecture 2
Lecture 2
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 

Recently uploaded

14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
SyedAbiiAzazi1
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
MdTanvirMahtab2
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
NidhalKahouli2
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
AJAYKUMARPUND1
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
yokeleetan1
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
Online aptitude test management system project report.pdf
Online aptitude test management system project report.pdfOnline aptitude test management system project report.pdf
Online aptitude test management system project report.pdf
Kamal Acharya
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
Osamah Alsalih
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
symbo111
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
WENKENLI1
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
An Approach to Detecting Writing Styles Based on Clustering Techniques
An Approach to Detecting Writing Styles Based on Clustering TechniquesAn Approach to Detecting Writing Styles Based on Clustering Techniques
An Approach to Detecting Writing Styles Based on Clustering Techniques
ambekarshweta25
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 

Recently uploaded (20)

14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application14 Template Contractual Notice - EOT Application
14 Template Contractual Notice - EOT Application
 
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
Pile Foundation by Venkatesh Taduvai (Sub Geotechnical Engineering II)-conver...
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
Swimming pool mechanical components design.pptx
Swimming pool  mechanical components design.pptxSwimming pool  mechanical components design.pptx
Swimming pool mechanical components design.pptx
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
Online aptitude test management system project report.pdf
Online aptitude test management system project report.pdfOnline aptitude test management system project report.pdf
Online aptitude test management system project report.pdf
 
MCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdfMCQ Soil mechanics questions (Soil shear strength).pdf
MCQ Soil mechanics questions (Soil shear strength).pdf
 
Building Electrical System Design & Installation
Building Electrical System Design & InstallationBuilding Electrical System Design & Installation
Building Electrical System Design & Installation
 
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdfGoverning Equations for Fundamental Aerodynamics_Anderson2010.pdf
Governing Equations for Fundamental Aerodynamics_Anderson2010.pdf
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
An Approach to Detecting Writing Styles Based on Clustering Techniques
An Approach to Detecting Writing Styles Based on Clustering TechniquesAn Approach to Detecting Writing Styles Based on Clustering Techniques
An Approach to Detecting Writing Styles Based on Clustering Techniques
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 

Lecture 12

  • 3. 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
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. Inheritance Inheritance in Java - Syntax public 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
  • 10. 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
  • 11. 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 method demo.Substraction(a, b); parent class method demo.multiplication(a, b); Child class method } } 11
  • 12. 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
  • 13. 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
  • 14. 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
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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 MessagePost username username message filename timestamp caption likes timestamp comments like comments 18
  • 19. Facebook Example Classes & Objects for Network Project What may be the possible method for these classes?
  • 20. Facebook Example Classes & Objects for Facebook Project  Here is complete class that shows both data and behaviour
  • 21. 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>(); }
  • 22. Facebook Example – MessagePost Class public void like() { likes++; } public void unlike() { if (likes > 0) { likes--; } } public void addComment(String text) { comments.add(text); }
  • 23. 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"; } }
  • 24. 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."); } } }
  • 25. Facebook Example – PhotoPost Class import 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>(); }
  • 26. Facebook Example – PhotoPost Class public void like() { likes++; } public void unlike() { if (likes > 0) { likes--; } } public void addComment(String text) { comments.add(text); }
  • 27. Facebook Example – PhotoPost Class public String getImageFile() { return filename; } public String getCaption() { return caption; } public long getTimeStamp() { return timestamp; }
  • 28. 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."); } }
  • 29. 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"; } } }
  • 30. 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>).
  • 31. 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); }
  • 32. 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 } } }
  • 33. Facebook Example Objects in Facebook Example
  • 34. 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.
  • 35. 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
  • 36. 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.
  • 37. Using Inheritance New Structure of Facebook Example
  • 38. 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
  • 39. Using Inheritance – Facebook Example Class Post import 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>(); }
  • 40. 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); }
  • 41. 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"; } }
  • 42. 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."); }
  • 43. Using Inheritance – Facebook Example Class MessagePost import 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"; }
  • 44. 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.
  • 45. 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
  • 46. Using Inheritance – Facebook Example Class PhotoPost import 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; }
  • 47. Using Inheritance – Facebook Example Class PhotoPost public String getImageFile() { return filename; } public String getCaption() { return caption; } }
  • 48. 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.
  • 49. Using Inheritance – Facebook Example Adding other Posts
  • 50. 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
  • 51. 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
  • 52. Using Inheritance – Facebook Example Solution to Change in Requrement
  • 53. Inheritance Class NewsFeed Import java.util.ArrayList; public class NewsFeed { private ArrayList<Post> posts; public NewsFeed() { posts = new ArrayList<Post>(); } public void addPost(Post post) { posts.add(post); }
  • 54. 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
  • 55. Inheritance Summarizing Inheritance Advantages  Recall the Inheritance advantages with Facebook example  Avoid Code Duplication  Code Reuse  Easier maintenance  Extendibility
  • 56. 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 A B inherits from A class C implements F C is a subtype of F both subtyping and inheritance just subtyping
  • 57. 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 method Calls class B’s display method Calls class B’s display method
  • 58. 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?
  • 59. 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();
  • 60. 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 Declarations Car c1 = new Vehicle(); // this is an error! Car c2 = new Bicycle(); // this is an error!
  • 61. 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){ . . . } }
  • 62. 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.
  • 63. 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 is for(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.
  • 64. 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.
  • 65. 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
  • 66. Casting Type Loss & Casting  Now consider this code fragment, in which Bicycle is also a subclass of Vehicle: Find which line will give error Vehicle 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
  • 67. 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.
  • 68. 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
  • 69. 69