This lecture discusses inheritance in object-oriented programming. It begins with an introduction to inheritance and why it is used. Inheritance allows classes to inherit properties like methods and fields from a parent or superclass. This avoids duplicating code and allows code reuse. The lecture then provides the syntax for inheritance in Java and gives an example to demonstrate inheritance. It shows how a subclass inherits from a superclass. The lecture ends by discussing some important points about inheritance in Java like how subclasses can override methods.
Interface in java ,multiple inheritance in java, interface implementationHoneyChintal
multiple inheritance in java, interface implementation, abstraction,
multiple inheritance in java using interface, how to use interface,
how to use java, how to execute a java code
Interface in java By Dheeraj Kumar Singhdheeraj_cse
In Java,
An interface is a way through which unrelated objects use to interact with one another.
Using interface, you can specify what a class must do, but not how it does it.
It is not a class but a set of requirements for classes that implement the interface.
Top 20 c# interview Question and answersw3asp dotnet
This presentation contains interview question and answers . www.w3asp.net provide you the information, knowledge, job, practices and tranings regarding asp.net.
Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
Members of a Java interface are public by default. A member of an abstract class can either be private, protected or public.
An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated, but can be invoked if it contains a main method.
20 most important java programming interview questionsGradeup
These questions are prepared by Java Programming Experts and solutions to these programs are asked during job interviews. Knowing solution to these questions helps you in getting a job.
Interface in java ,multiple inheritance in java, interface implementationHoneyChintal
multiple inheritance in java, interface implementation, abstraction,
multiple inheritance in java using interface, how to use interface,
how to use java, how to execute a java code
Interface in java By Dheeraj Kumar Singhdheeraj_cse
In Java,
An interface is a way through which unrelated objects use to interact with one another.
Using interface, you can specify what a class must do, but not how it does it.
It is not a class but a set of requirements for classes that implement the interface.
Top 20 c# interview Question and answersw3asp dotnet
This presentation contains interview question and answers . www.w3asp.net provide you the information, knowledge, job, practices and tranings regarding asp.net.
Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
Members of a Java interface are public by default. A member of an abstract class can either be private, protected or public.
An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot be instantiated, but can be invoked if it contains a main method.
20 most important java programming interview questionsGradeup
These questions are prepared by Java Programming Experts and solutions to these programs are asked during job interviews. Knowing solution to these questions helps you in getting a job.
Inheritance in java introduces the concept of reusability by implementing a mechanism in which one object acquires all the properties and behaviors of the parent object.
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOPs (Object Oriented programming system).
The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
This all is about the object oriented programming in c++ language. It includes the importent components of oops , related terminologies and the related details.
it describes the main concepts of object oriented programming
For more posts : http://comsciguide.blogspot.com/
For full playlist of Interview puzzles videos : https://www.youtube.com/playlist?list=PL3v9ipJOEEPfI4zt4ExamGJwndkvg0SFc
24 standard interview puzzles: https://www.youtube.com/playlist?list=PL3v9ipJOEEPefIF4nscYOobim1iRBJTjw
Aptitude training playlist link : https://www.youtube.com/playlist?list=PL3v9ipJOEEPfumKHa02HWjCfPvGQiPZiG
for C and C++ questions, that are asked in the interviews, go through the posts in the link : http://comsciguide.blogspot.com/
for more videos, my youtube channel : https://www.youtube.com/channel/UCvMy2V7gYW7VR2WgyvLj3-A
Inheritance in Java beginner to advance with examples.pptxnaeemcse
Dive into the world of Java Inheritance and discover how it forms the backbone of robust and scalable code architecture. Learn how this powerful object-oriented programming concept allows you to effortlessly reuse and extend existing code, promoting a modular and maintainable design. Whether you're a novice or a seasoned developer, grasp the key principles of inheritance and elevate your Java programming skills. Join us on this journey to empower your code with the inheritance advantage, setting the stage for efficient development and enhanced software flexibility. Don't miss out on this essential building block for creating elegant and efficient Java applications!Unlock the potential of Java Inheritance with a concise exploration of single, multiple, multilevel, and hierarchical types. Discover how each type enhances code structure and flexibility. Elevate your Java skills by understanding the nuances of inheritance, optimizing code for efficiency and maintainability. Join us on this journey of code mastery and harness the diverse power of inheritance in your Java projects.
Industrial Training at Shahjalal Fertilizer Company Limited (SFCL)MdTanvirMahtab2
This presentation is about the working procedure of Shahjalal Fertilizer Company Limited (SFCL). A Govt. owned Company of Bangladesh Chemical Industries Corporation under Ministry of Industries.
6th International Conference on Machine Learning & Applications (CMLA 2024)ClaraZara1
6th International Conference on Machine Learning & Applications (CMLA 2024) will provide an excellent international forum for sharing knowledge and results in theory, methodology and applications of on Machine Learning & Applications.
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsVictor Morales
K8sGPT is a tool that analyzes and diagnoses Kubernetes clusters. This presentation was used to share the requirements and dependencies to deploy K8sGPT in a local environment.
Understanding Inductive Bias in Machine LearningSUTEJAS
This presentation explores the concept of inductive bias in machine learning. It explains how algorithms come with built-in assumptions and preferences that guide the learning process. You'll learn about the different types of inductive bias and how they can impact the performance and generalizability of machine learning models.
The presentation also covers the positive and negative aspects of inductive bias, along with strategies for mitigating potential drawbacks. We'll explore examples of how bias manifests in algorithms like neural networks and decision trees.
By understanding inductive bias, you can gain valuable insights into how machine learning models work and make informed decisions when building and deploying them.
Online aptitude test management system project report.pdfKamal Acharya
The purpose of on-line aptitude test system is to take online test in an efficient manner and no time wasting for checking the paper. The main objective of on-line aptitude test system is to efficiently evaluate the candidate thoroughly through a fully automated system that not only saves lot of time but also gives fast results. For students they give papers according to their convenience and time and there is no need of using extra thing like paper, pen etc. This can be used in educational institutions as well as in corporate world. Can be used anywhere any time as it is a web based application (user Location doesn’t matter). No restriction that examiner has to be present when the candidate takes the test.
Every time when lecturers/professors need to conduct examinations they have to sit down think about the questions and then create a whole new set of questions for each and every exam. In some cases the professor may want to give an open book online exam that is the student can take the exam any time anywhere, but the student might have to answer the questions in a limited time period. The professor may want to change the sequence of questions for every student. The problem that a student has is whenever a date for the exam is declared the student has to take it and there is no way he can take it at some other time. This project will create an interface for the examiner to create and store questions in a repository. It will also create an interface for the student to take examinations at his convenience and the questions and/or exams may be timed. Thereby creating an application which can be used by examiners and examinee’s simultaneously.
Examination System is very useful for Teachers/Professors. As in the teaching profession, you are responsible for writing question papers. In the conventional method, you write the question paper on paper, keep question papers separate from answers and all this information you have to keep in a locker to avoid unauthorized access. Using the Examination System you can create a question paper and everything will be written to a single exam file in encrypted format. You can set the General and Administrator password to avoid unauthorized access to your question paper. Every time you start the examination, the program shuffles all the questions and selects them randomly from the database, which reduces the chances of memorizing the questions.
Student information management system project report ii.pdfKamal Acharya
Our project explains about the student management. This project mainly explains the various actions related to student details. This project shows some ease in adding, editing and deleting the student details. It also provides a less time consuming process for viewing, adding, editing and deleting the marks of the students.
An Approach to Detecting Writing Styles Based on Clustering Techniquesambekarshweta25
An Approach to Detecting Writing Styles Based on Clustering Techniques
Authors:
-Devkinandan Jagtap
-Shweta Ambekar
-Harshit Singh
-Nakul Sharma (Assistant Professor)
Institution:
VIIT Pune, India
Abstract:
This paper proposes a system to differentiate between human-generated and AI-generated texts using stylometric analysis. The system analyzes text files and classifies writing styles by employing various clustering algorithms, such as k-means, k-means++, hierarchical, and DBSCAN. The effectiveness of these algorithms is measured using silhouette scores. The system successfully identifies distinct writing styles within documents, demonstrating its potential for plagiarism detection.
Introduction:
Stylometry, the study of linguistic and structural features in texts, is used for tasks like plagiarism detection, genre separation, and author verification. This paper leverages stylometric analysis to identify different writing styles and improve plagiarism detection methods.
Methodology:
The system includes data collection, preprocessing, feature extraction, dimensional reduction, machine learning models for clustering, and performance comparison using silhouette scores. Feature extraction focuses on lexical features, vocabulary richness, and readability scores. The study uses a small dataset of texts from various authors and employs algorithms like k-means, k-means++, hierarchical clustering, and DBSCAN for clustering.
Results:
Experiments show that the system effectively identifies writing styles, with silhouette scores indicating reasonable to strong clustering when k=2. As the number of clusters increases, the silhouette scores decrease, indicating a drop in accuracy. K-means and k-means++ perform similarly, while hierarchical clustering is less optimized.
Conclusion and Future Work:
The system works well for distinguishing writing styles with two clusters but becomes less accurate as the number of clusters increases. Future research could focus on adding more parameters and optimizing the methodology to improve accuracy with higher cluster values. This system can enhance existing plagiarism detection tools, especially in academic settings.
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
}
}
}
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.
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.
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
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
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