This document provides an introduction to object-oriented programming (OOP) concepts in Java, including encapsulation, inheritance, polymorphism, and abstraction. It discusses each concept in detail with examples in Java code. It also covers the different types of inheritance in Java such as single, multiple, multilevel, and hybrid inheritance. The document explains that while multiple inheritance is not directly supported in Java, it can be achieved using interfaces. Overall, the document serves as a guide to learning OOP concepts and their implementation in Java.
Abstract: This PDSG workshop covers the basics of OOP programming in Python. Concepts covered are class, object, scope, method overloading and inheritance.
Level: Fundamental
Requirements: One should have some knowledge of programming.
Abstract: This PDSG workshop covers the basics of OOP programming in Python. Concepts covered are class, object, scope, method overloading and inheritance.
Level: Fundamental
Requirements: One should have some knowledge of programming.
This is the presentation file about inheritance in java. You can learn details about inheritance and method overriding in inheritance in java. I think it's can help your. Thank you.
Learn the various forms of polymorphism in Java with illustrative examples to explain method overloading(Compile-time polymorphism) and method overriding(Run-time polymorphism)
Data abstraction is the process of hiding certain details and showing only essential information to the user.
Interfaces and Abstract classes.
Contains abstract keyword also.
Presented by: N.V.RajaSekhar Reddy
www.technolamp.co.in
Want more interesting...
Watch and Like us @ https://www.facebook.com/Technolamp.co.in
subscribe videos @ http://www.youtube.com/user/nvrajasekhar
This is the presentation file about inheritance in java. You can learn details about inheritance and method overriding in inheritance in java. I think it's can help your. Thank you.
Learn the various forms of polymorphism in Java with illustrative examples to explain method overloading(Compile-time polymorphism) and method overriding(Run-time polymorphism)
Data abstraction is the process of hiding certain details and showing only essential information to the user.
Interfaces and Abstract classes.
Contains abstract keyword also.
Presented by: N.V.RajaSekhar Reddy
www.technolamp.co.in
Want more interesting...
Watch and Like us @ https://www.facebook.com/Technolamp.co.in
subscribe videos @ http://www.youtube.com/user/nvrajasekhar
If you're developing Java for devices or embedded applications, you have a new Java runtime option. Zulu Embedded offers 100% open source, fully customized builds of OpenJDK (Java SE 8, 7 and 6) with world-class support and flexible licensing.
Java OOP Programming language (Part 6) - Abstract Class & InterfaceOUM SAOKOSAL
Java OOP Programming language (Part 6) - Abstract Class & Interface
Oum Saokosal
Where to me find me more:
YouTube: https://www.youtube.com/user/oumsaokosal
FB Page: https://facebook.com/kosalgeek
PPT: https://www.slideshare.net/oumsaokosal
Twitter: https://twitter.com/okosal
Web: http://kosalgeek.com
Presentation by Dr. Cliff Click, Jr. Mention Java performance to a C hacker, or vice versa, and a flame war will surely ensue. The Web is full of broken benchmarks and crazy claims about Java and C performance. This session will aim to give a fair(er) comparison between the languages, striving to give a balanced view of each language's various strengths and weaknesses. It will also point out what's broken about many of the Java-versus-C Websites, so when you come across one, you can see the flaws and know that the Website isn't telling you what it (generally) claims to be telling you. (It's surely telling you "something," but almost just as surely is "not realistically" telling you why X is better than Y).
Object oriented programming (oop) cs304 power point slides lecture 01Adil Kakakhel
this is the first lecture developed by virtual university of pakist about object oriented programming. very useful and a start from the very basics about OO modeling.
Introduction to Object Oriented ProgrammingMoutaz Haddara
An Introduction to Object-Oriented Programming (OOP)
Download the presentation to view it correctly, as it has some animations that won't show here.
If you have any questions, please contact me. You are free to use it this presentation, but it would be nice at least to give me some credit :)
Content:
1- History of Programming
2. Objects and Classes
3- Abstraction, Inheritance, Encapsulation, and Polymorphism
OOP
As the name suggests, Object-Oriented Programming or OOPs refers to languages that use objects in programming. Object-oriented programming aims to implement real-world entities like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind together the data and the functions that operate on them so that no other part of the code can access this data except that function.
OOPs Concepts:
Class
Objects
Data Abstraction
Encapsulation
Inheritance
Polymorphism
Dynamic Binding
Message Passing
1. Class:
A class is a user-defined data type. It consists of data members and member functions, which can be accessed and used by creating an instance of that class. It represents the set of properties or methods that are common to all objects of one type. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and brands but all of them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage are their properties.
2. Object:
It is a basic unit of Object-Oriented Programming and represents the real-life entities. An Object is an instance of a Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an object is created) memory is allocated. An object has an identity, state, and behavior. Each object contains data and code to manipulate the data. Objects can interact without having to know details of each other’s data or code, it is sufficient to know the type of message accepted and type of response returned by the objects.
For example “Dog” is a real-life Object, which has some characteristics like color, Breed, Bark, Sleep, and Eats.
Object in OOPs
Object
3. Data Abstraction:
Data abstraction is one of the most essential and important features of object-oriented programming. Data abstraction refers to providing only essential information about the data to the outside world, hiding the background details or implementation. Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators will increase the speed of the car or applying brakes will stop the car, but he does not know about how on pressing the accelerator the speed is increasing, he does not know about the inner mechanism of the car or the implementation of the accelerator, brakes, etc in the car. This is what abstraction is.
4. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds together code and the data it manipulates. In Encapsulation, the variables or data of a class are hidden from any other class and can be accessed only through any member function of their class in which they are declared. As in encapsulation, the data in a class is hidden from other classes, so it is also known as data-hiding.
Encapsulation in Object Oriented Pro
What a lot of people don't realize is that Google has a lot of powerful tricks hidden up it's sleeve. Here are some of those commands and how they can be best used by a developer.
Connector Corner: Automate dynamic content and events by pushing a buttonDianaGray10
Here is something new! In our next Connector Corner webinar, we will demonstrate how you can use a single workflow to:
Create a campaign using Mailchimp with merge tags/fields
Send an interactive Slack channel message (using buttons)
Have the message received by managers and peers along with a test email for review
But there’s more:
In a second workflow supporting the same use case, you’ll see:
Your campaign sent to target colleagues for approval
If the “Approve” button is clicked, a Jira/Zendesk ticket is created for the marketing design team
But—if the “Reject” button is pushed, colleagues will be alerted via Slack message
Join us to learn more about this new, human-in-the-loop capability, brought to you by Integration Service connectors.
And...
Speakers:
Akshay Agnihotri, Product Manager
Charlie Greenberg, Host
Search and Society: Reimagining Information Access for Radical FuturesBhaskar Mitra
The field of Information retrieval (IR) is currently undergoing a transformative shift, at least partly due to the emerging applications of generative AI to information access. In this talk, we will deliberate on the sociotechnical implications of generative AI for information access. We will argue that there is both a critical necessity and an exciting opportunity for the IR community to re-center our research agendas on societal needs while dismantling the artificial separation between the work on fairness, accountability, transparency, and ethics in IR and the rest of IR research. Instead of adopting a reactionary strategy of trying to mitigate potential social harms from emerging technologies, the community should aim to proactively set the research agenda for the kinds of systems we should build inspired by diverse explicitly stated sociotechnical imaginaries. The sociotechnical imaginaries that underpin the design and development of information access technologies needs to be explicitly articulated, and we need to develop theories of change in context of these diverse perspectives. Our guiding future imaginaries must be informed by other academic fields, such as democratic theory and critical theory, and should be co-developed with social science scholars, legal scholars, civil rights and social justice activists, and artists, among others.
Essentials of Automations: Optimizing FME Workflows with ParametersSafe Software
Are you looking to streamline your workflows and boost your projects’ efficiency? Do you find yourself searching for ways to add flexibility and control over your FME workflows? If so, you’re in the right place.
Join us for an insightful dive into the world of FME parameters, a critical element in optimizing workflow efficiency. This webinar marks the beginning of our three-part “Essentials of Automation” series. This first webinar is designed to equip you with the knowledge and skills to utilize parameters effectively: enhancing the flexibility, maintainability, and user control of your FME projects.
Here’s what you’ll gain:
- Essentials of FME Parameters: Understand the pivotal role of parameters, including Reader/Writer, Transformer, User, and FME Flow categories. Discover how they are the key to unlocking automation and optimization within your workflows.
- Practical Applications in FME Form: Delve into key user parameter types including choice, connections, and file URLs. Allow users to control how a workflow runs, making your workflows more reusable. Learn to import values and deliver the best user experience for your workflows while enhancing accuracy.
- Optimization Strategies in FME Flow: Explore the creation and strategic deployment of parameters in FME Flow, including the use of deployment and geometry parameters, to maximize workflow efficiency.
- Pro Tips for Success: Gain insights on parameterizing connections and leveraging new features like Conditional Visibility for clarity and simplicity.
We’ll wrap up with a glimpse into future webinars, followed by a Q&A session to address your specific questions surrounding this topic.
Don’t miss this opportunity to elevate your FME expertise and drive your projects to new heights of efficiency.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
JMeter webinar - integration with InfluxDB and GrafanaRTTS
Watch this recorded webinar about real-time monitoring of application performance. See how to integrate Apache JMeter, the open-source leader in performance testing, with InfluxDB, the open-source time-series database, and Grafana, the open-source analytics and visualization application.
In this webinar, we will review the benefits of leveraging InfluxDB and Grafana when executing load tests and demonstrate how these tools are used to visualize performance metrics.
Length: 30 minutes
Session Overview
-------------------------------------------
During this webinar, we will cover the following topics while demonstrating the integrations of JMeter, InfluxDB and Grafana:
- What out-of-the-box solutions are available for real-time monitoring JMeter tests?
- What are the benefits of integrating InfluxDB and Grafana into the load testing stack?
- Which features are provided by Grafana?
- Demonstration of InfluxDB and Grafana using a practice web application
To view the webinar recording, go to:
https://www.rttsweb.com/jmeter-integration-webinar
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
UiPath Test Automation using UiPath Test Suite series, part 4
Object+oriented+programming+in+java
1. OOP In Java Page 1
Object Oriented Programming
In Java
There are two ways to write error-free programs; only the third one works.
(Alan J. Perlis)
Author: Ye Win
Major: Java Programming
Contacts: http://www.slideshare.net/mysky14,
http://stackoverflow.com/users/4352728/ye-
win, https://www.linkedin.com/pub/ye-
Java Developers Guide Theoretical
Practical &
Role Playing
Easy Learning
2. TABLE OF CONTENTS
OOPS IN JAVA- ENCAPSULATION, INHERITANCE, POLYMORPHISM, ABSTRACTION 3
OBJECTORIENTED APPROACH: AN INTRODUCTION 3
PRINCIPLES OF OOPS 4
1) ENCAPSULATION 4
2) INHERITANCE 5
3) POLYMORPHISM 6
OOPS IN JAVA WITH EXAMPLE 7
1) ENCAPSULATIONIN JAVA WITH EXAMPLES 7
2) TYPES OF INHERITANCE IN JAVA 10
3) WHY MULTIPLE INHERITANCE IS NOT SUPPORTED IN JAVA 21
4) POLYMORPHISM IN JAVA – METHOD OVERLOADING AND OVERRIDING 25
5) DIVING DEEPER INTO POLYMORPHISM 31
6) COVARIANT RETURN TYPE IN JAVA 41
OOP In Java Page 2
4. OOPs in Java- Encapsulation, Inheritance,
Polymorphism, Abstraction
Object Oriented Approach: An Introduction
OOP In Java Page 4
One of the most fundamental concepts of OOPs is Abstraction. Abstraction is a powerful
methodology to manage complex systems. Abstraction is managed by well-defined objects and their
hierarchical classification.
Java is an object oriented language because it provides the features to implement an object oriented
model. These features include encapsulation, inheritance and polymorphism.
OOPS is about developing an application around its data, i.e. objects which provides the access to
their properties and the possible operations in their own way.
5. Principles of OOPs
1) Encapsulation
Below is a real-life example of encapsulation. For the example program and more details on this
concept refer encapsulation in java with example.
Encapsulation is the ability to package data, related behavior in an object bundle and control/restrict
access to them (both data and function) from other objects. It is all about packaging related stuff
together and hide them from external elements.
When we design a class in OOP, the first principle we should have in mind is encapsulation. Group the
related data and its behavior in a bucket. Primary benefit of encapsulation is, better maintainability.
Similarly, same concept of encapsulation can be applied to code. Encapsulated code should have
following characteristics:
Everyone knows how to access it.
Can be easily used regardless of implementation details.
There shouldn’t any side effects of the code, to the rest of the application.
OOP In Java Page 5
6. 2) Inheritance
Below is a theoretical explanation of inheritance with real-life examples. For detailed explanation on
this topic refer types of inheritance in java and Why Multiple Inheritance is Not Supported in Java.
Inheritance is the mechanism by which an object acquires the some or all properties of another
object.
It supports the concept of hierarchical classification.
Inheritance is one of the features of Object-Oriented Programming (OOPs). Inheritance allows a class
to use the properties and methods of another class. In other words, the derived class inherits the
states and behaviors from the base class. The derived class is also called subclass and the base class is
also known as super-class. The derived class can add its own additional variables and methods. These
additional variable and methods differentiates the derived class from the base class.
Inheritance is a compile-time mechanism. A super-class can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not support multiple inheritance.
The superclass and subclass have “is-a” relationship between them. Let’s have a look at the example
below.
OOP In Java Page 6
7. 3) Polymorphism
Below is a real-life example of polymorphism. For the example program and more details on this OOP
concept refer runtime & compile time polymorphism.
OOP In Java Page 7
Polymorphism means to process objects differently based on their data type.
In other words it means, one method with multiple implementation, for a certain class of action.
And which implementation to be used is decided at runtime depending upon the situation (i.e.,
data type of the object)
This can be implemented by designing a generic interface, which provides generic methods for a
certain class of action and there can be multiple classes, which provides the implementation of
these generic methods.
Polymorphism could be static and dynamic both. Overloading is static polymorphism while, overriding
is dynamic polymorphism.
Overloading in simple words means two methods having same method name but takes different
input parameters. This called static because, which method to be invoked will be decided at the
time of compilation
Overriding means a derived class is implementing a method of its super class.
8. OOPS in Java with Example
1) Encapsulation in java with examples
What is encapsulation?
OOP In Java Page 8
The whole idea behind encapsulation is to hide the implementation details from users. If a data
member is private it means it can only be accessed within the same class. No outside class can access
private data member (variable) of other class. However if we setup public getter and setter methods
to update (for e.g. void setSSN(int ssn))and read (for e.g. int getSSN()) the private data fields then the
outside class can access those private data fields via public methods. This way data can only be
accessed by public methods thus making the private fields and their implementation hidden for
outside classes. That’s why encapsulation is known as data hiding. Let’s see an example to
understand this concept better.
public class EncapsulationDemo{
private int ssn;
private String empName;
private int empAge;
//Getter and Setter methods
public int getEmpSSN(){
return ssn;
}
public String getEmpName(){
return empName;
}
public int getEmpAge(){
return empAge;
}
9. public void setEmpAge(int newValue){
empAge = newValue;
}
public void setEmpName(String newValue){
empName = newValue;
}
public void setEmpSSN(int newValue){
ssn = newValue;
}
}
public class EncapsTest{
public static void main(String args[]){
EncapsulationDemo obj = new EncapsulationDemo();
obj.setEmpName("Mario");
obj.setEmpAge(32);
obj.setEmpSSN(112233);
System.out.println("Employee Name: " + obj.getEmpName());
System.out.println("Employee SSN: " + obj.getEmpSSN());
System.out.println("Employee Age: " + obj.getEmpAge());
}
}
Output:
Employee Name: Mario
Employee SSN: 112233
Employee Age: 32
In above example all the three data members (or data fields) are private which cannot be accessed
directly. These fields can be accessed via public methods only. Fields empName,ssn and empAge are
made hidden data fields using encapsulation technique of OOPs.
OOP In Java Page 9
10. Advantages of encapsulation:
1. It improves maintainability and flexibility and re-usability: for e.g. In the above code the
implementation code of void setEmpName(String name) and String
getEmpName()can be changed at any point of time. Since the implementation is purely hidden
for outside classes they would still be accessing the private field empName using the same
methods (setEmpName(String name) and getEmpName()). Hence the code can be
maintained at any point of time without breaking the classes that uses the code. This improves
the re-usability of the underlying class.
2. The fields can be made read-only (If we don’t define setter methods in the class) or write-only (If
we don’t define the getter methods in the class). For e.g. If we have a field(or variable) which
doesn’t need to change at any cost then we simply define the variable as private and instead of
set and get both we just need to define the get method for that variable. Since the set method is
not present there is no way an outside class can modify the value of that field.
3. User would not be knowing what is going on behind the scene. They would only be knowing that
to update a field call set method and to read a field call get method but what these set and
get methods are doing is purely hidden from them.
OOP In Java Page
10
11. 2) Types of inheritance in java
Types of inheritance in Java: Single, Multiple, Multilevel & Hybrid
Below are various types of inheritance in Java. We will see each one of them one by one with the help
of examples and flow diagrams.
1) Single Inheritance
Single inheritance is damn easy to understand. When a class extends another one class only then we
call it a single inheritance. The below flow diagram shows that class B extends only one class which is
A. Here A is a parent class of B and B would be a child class of A.
Single Inheritance example program in Java
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
OOP In Java Page 10
12. }
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
OOP In Java Page 12
13. 2) Multiple Inheritance
“Multiple Inheritance” refers to the concept of one class extending (Or inherits) more than one base
class. The inheritance we learnt earlier had the concept of one base class or parent. The problem with
“multiple inheritance” is that the derived class will have to manage the dependency on two base
classes.
Note 1: Multiple Inheritance is very rarely used in software projects. Using Multiple inheritance often
leads to problems in the hierarchy. This results in unwanted complexity when further extending the
class.
Note 2: Most of the new OO languages like Small Talk, Java, C# do not support Multiple inheritance.
Multiple Inheritance is supported in C++.
OOP In Java Page 13
14. 3) Multilevel Inheritance
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a
derived class, thereby making this derived class the base class for the new class. As you can see in
below flow diagram C is subclass or child class of B and B is a child class of A.
Multilevel Inheritance example program in Java
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
OOP In Java Page 14
15. {
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}
OOP In Java Page 15
16. 4) Hierarchical Inheritance
In such kind of inheritance one class is inherited by many sub classes. In below example class B, C and
D inherits the same class A. A is parent class (or base class) of B, C & D.
Hierarchical Inheritance example program in Java
Class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
Class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
Class D extends A
{
OOP In Java Page 16
17. public void methodD()
{
System.out.println("method of Class D");
}
}
Class MyClass
{
public void methodB()
{
System.out.println("method of Class B");
}
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}
OOP In Java Page 17
The above would run perfectly fine with no errors and the output would be –
method of Class A
method of Class A
method of Class A
18. 5) Hybrid Inheritance
In simple terms you can say that Hybrid inheritance is a combination
of Single and Multipleinheritance. A typical flow diagram would look like below. A hybrid inheritance
can be achieved in the java in a same way as multiple inheritance can be!! Using interfaces. yes you
heard it right. By using interfaces you can have multiple as well as hybrid inheritance in Java.
Hybird Inheritance example program in Java
Example program 1: Using classes to form hybrid
public class A
{
public void methodA()
{
System.out.println("Class A methodA");
}
}
public class B extends A
{
public void methodA()
{
System.out.println("Child class B is overriding inherited method A");
}
public void methodB()
{
System.out.println("Class B methodB");
OOP In Java Page 18
19. }
}
public class C extends A
{
public void methodA()
{
System.out.println("Child class C is overriding the methodA");
}
public void methodC()
{
System.out.println("Class C methodC");
}
}
public class D extends B, C
{
public void methodD()
{
System.out.println("Class D methodD");
}
public static void main(String args[])
{
D obj1= new D();
obj1.methodD();
obj1.methodA();
}
}
OOP In Java Page 19
Output:
Error!!
Why? Most of the times you will find the following explanation of above error – Multiple inheritance
is not allowed in java so class D cannot extend two classes (B and C). But do you know why it’s not
allowed? Let’s look at the above code once again, In the above program class B and C both are
extending class A and they both have overridden the methodA(), which they can do as they have
extended the class A. But since both have different version of methodA(), compiler is confused which
20. one to call when there has been a call made to methodA() in child class D (child of both B and C, it’s
object is allowed to call their methods), this is a ambiguous situation and to avoid it, such kind of
scenarios are not allowed in java. In C++ it’s allowed.
What’s the solution? Hybrid inheritance implementation using interfaces.
interface A
{
public void methodA();
}
interface B extends A
{
public void methodB();
}
interface C extends A
{
public void methodC();
}
class D implements B, C
{
public void methodA()
{
System.out.println("MethodA");
}
public void methodB()
{
System.out.println("MethodB");
}
public void methodC()
{
System.out.println("MethodC");
}
public static void main(String args[])
{
D obj1= new D();
OOP In Java Page 20
21. obj1.methodA();
obj1.methodB();
obj1.methodC();
}
}
OOP In Java Page 20
Output:
MethodA
MethodB
MethodC
Note: Even though class D didn’t implement interface “A” still we have to define the methodA() in it.
It is because interface B and C extends the interface A.
The above code would work without any issues and that’s how we implemented hybrid inheritance in
java using interfaces.
22. 3) Why Multiple Inheritance is Not Supported in Java
In a white paper titled “Java: an Overview” by James Gosling in February 1995 gives an idea on why
multiple inheritance is not supported in Java.
OOP In Java Page 22
“JAVA omits many rarely used, poorly understood, confusing features of C++ that in our experience
bring more grief than benefit. This primarily consists of operator overloading (although it does have
method overloading), multiple inheritance, and extensive automatic coercions.”
Who better than Dr. James Gosling is qualified to make a comment on this? This paragraph gives us
an overview and he touches this topic of not supporting multiple-inheritance.
Java does not support multiple inheritance
First let’s nail this point. This itself is a point of discussion, whether java supports multiple inheritance
or not. Some say, it supports using interface. No. There is no support for multiple inheritance in java. If
you do not believe my words, read the above paragraph again and those are words of the father of
Java.
This story of supporting multiple inheritance using interface is what we developers cooked up.
Interface gives flexibility than concrete classes and we have option to implement multiple interface
using single class. This is by agreement we are adhering to two blueprints to create a class.
This is trying to get closer to multiple inheritance. What we do is implement multiple interface, here
we are not extending (inheriting) anything. The implementing class is the one that is going to add the
properties and behavior. It is not getting the implementation free from the parent classes. I would
simply say, there is no support for multiple inheritance in java.
Multiple Inheritance
Multiple inheritance is where we inherit the properties and behavior of multiple classes to a single
class. C++, Common Lisp, are some popular languages that support multiple inheritance.
23. Why Java does not support multiple inheritance?
Now we are sure that there is no support for multiple inheritance in java. But why? This is a design
decision taken by the creators of java. The keyword is simplicity and rare use.
Simplicity
I want to share the definition for java given by James Gosling.
JAVA: A simple, object oriented, distributed, interpreted, robust, secure, architecture neutral, portable,
high performance, multithreaded, dynamic language.
Look at the beauty of this definition for java. This should be the definition for a modern software
language. What is the first characteristic in the language definition? It is simple.
In order to enforce simplicity should be the main reason for omitting multiple inheritance. For
instance, we can consider diamond problem of multiple inheritance.
OOP In Java Page 23
24. We have two classes B and C inheriting from A. Assume that B and C are overriding an inherited
method and they provide their own implementation. Now D inherits from both B and C doing multiple
inheritance. D should inherit that overridden method, which overridden method will be used? Will it
be from B or C? Here we have an ambiguity.
In C++ there is a possibility to get into this trap though it provides alternates to solve this. In java this
can never occur as there is no multiple inheritance. Here even if two interfaces are going to have
same method, the implementing class will have only one method and that too will be done by
the implementer. Dynamic loading of classes makes the implementation of multiple inheritance
difficult.
Rarely Used
We have been using java for long now. How many times have we faced a situation where we are
stranded and facing the wall because of the lack of support for multiple inheritance in java? With my
personal experience I don’t remember even once. Since it is rarely required, multiple inheritance can
be safely omitted considering the complexity it has for implementation. It is not worth the hassle and
the path of simplicity is chosen.
Even if it is required it can be substituted with alternate design. So it is possible to live without
multiple inheritance without any issues and that is also one reason.
OOP In Java Page 24
25. My opinion on this is, omitting support for multiple inheritance in java is not a flaw and it is good for
the implementers.
OOP In Java Page 25
26. 4) Polymorphism in Java – Method Overloading and Overriding
What is Polymorphism in Programming?
Polymorphism is the capability of a method to do different things based on the object that it is acting
upon. In other words, polymorphism allows you define one interface and have multiple
implementations. I know it sounds confusing. Don’t worry we will discuss this in detail.
It is a feature that allows one interface to be used for a general class of actions.
An operation may exhibit different behavior in different instances.
The behavior depends on the types of data used in the operation.
It plays an important role in allowing objects having different internal structures to share the same
external interface.
Polymorphism is extensively used in implementing inheritance.
Following concepts demonstrate different types of polymorphism in java.
1) Method Overloading
2) Method Overriding
Method Definition:
A method is a set of code which is referred to by name and can be called (invoked) at any point in a
program simply by utilizing the method’s name.
OOP In Java Page 26
27. 1) Method Overloading
1. To call an overloaded method in Java, it is must to use the type and/or number of arguments to
determine which version of the overloaded method to actually call.
2. Overloaded methods may have different return types; the return type alone is insufficient to
distinguish two versions of a method. .
3. When Java encounters a call to an overloaded method, it simply executes the version of the
method whose parameters match the arguments used in the call.
4. It allows the user to achieve compile time polymorphism.
5. An overloaded method can throw different exceptions.
6. It can have different access modifiers.
Example:
OOP In Java Page 27
class Overload
{
void demo (int a)
{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class MethodOverloading
{
public static void main (String args [])
{
Overload Obj = new Overload();
double result;
28. Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}
Here the method demo() is overloaded 3 times: first having 1 int parameter, second one has 2 int
parameters and third one is having double arg. The methods are invoked or called with the same type
and number of parameters used.
Output:
a: 10
a and b: 10,20
double a: 5.5
O/P : 30.25
Rules for Method Overloading
1. Overloading can take place in the same or in its sub-class.
2. Constructor in Java can be overloaded
3. Overloaded methods must have a different argument list.
4. Overloaded method should always be in part of the same class, with same name but different
parameters.
5. The parameters may differ in their type or number, or in both.
6. They may have the same or different return types.
7. It is also known as compile time polymorphism.
OOP In Java Page 28
29. 2) Method Overriding
Child class has the same method as of base class. In such cases child class overrides the parent class
method without even touching the source code of the base class. This feature is known as method
overriding.
Example:
public class BaseClass
{
public void methodToOverride() //Base class method
{
System.out.println ("I'm the method of BaseClass");
}
}
public class DerivedClass extends BaseClass
{
public void methodToOverride() //Derived Class method
{
System.out.println ("I'm the method of DerivedClass");
}
}
public class TestMethod
{
public static void main (String args []) {
// BaseClass reference and object
BaseClass obj1 = new BaseClass();
// BaseClass reference but DerivedClass object
BaseClass obj2 = new DerivedClass();
// Calls the method from BaseClass class
obj1.methodToOverride();
//Calls the method from DerivedClass class
obj2.methodToOverride();
}
}
OOP In Java Page 29
30. Output:
I'm the method of BaseClass
I'm the method of DerivedClass
Rules for Method Overriding:
1. applies only to inherited methods
2. object type (NOT reference variable type) determines which overridden method will be used at
runtime
3. Overriding methods must have the same return type
4. Overriding method must not have more restrictive access modifier
5. Abstract methods must be overridden
6. Static and final methods cannot be overridden
7. Constructors cannot be overridden
8. It is also known as Runtime polymorphism.
super keyword in Overriding:
When invoking a superclass version of an overridden method the super keyword is used.
Example:
OOP In Java Page 30
class Vehicle {
public void move () {
System.out.println ("Vehicles are used for moving from one place to another ");
}
}
class Car extends Vehicle {
public void move () {
super.move (); // invokes the super class method
System.out.println ("Car is a good medium of transport ");
}
31. }
public class TestCar {
public static void main (String args []){
Vehicle b = new Car (); // Vehicle reference but Car object
b.move (); //Calls the method in Car class
}
}
OOP In Java Page 30
Output:
Vehicles are used for moving from one place to another
Car is a good medium of transport
32. 5) Diving Deeper Into Polymorphism
Ability of an organism to take different shapes is polymorphism in bio world. A simplest definition in
computer terms would be, handling different data types using the same interface. In this tutorial, we
will learn about what is polymorphism in computer science and how polymorphism can be used in
Java.
I wish below tutorial will help a lot.
OOP In Java Page 32
is overloading polymorphism?
is overriding polymorphism?
Ad hoc Polymorphism
Parametric Polymorphism
Coercion Polymorphism
Inclusion or subtype Polymorphism
what is static-binding?
what is dynamic binding?
Types of Polymorphism
Polymorphism in computer science was introduced in 1967 by Christopher Strachey. Please let me
know with reference if it is not a fact and the tutorial can be updated. Following are the two major
types of polymorphism as defined by Strachey.
1. Ad hoc Polymorphism
2. Parametric Polymorphism
Later these were further categorized as below:
34. Ad hoc Polymorphism
"Ad-hoc polymorphism is obtained when a function works, or appears to work, on several different
types (which may not exhibit a common structure) and may behave in unrelated ways for each
type. Parametric polymorphism is obtained when a function works uniformly on a range of types;
these types normally exhibit some common structure." – Strachey 1967
If we want to say the above paragraph in two words, they are operator overloading and function
overloading. Determining the operation of a function based on the arguments passed.
Ad hoc Polymorphism in Java
In Java we have function overloading and we do not have operator overloading. Yes we have “+”
operator implemented in a polymorphic way.
String fruits = "Apple" + "Orange";
int a = b + c;
The definition is when the type is different, the internal function adjusts itself accordingly. int and
float are different types and so even the following can be included in polymorphism operator
overloading.
int i = 10 - 3;
float f = 10.5 - 3.5;
Similarly even * and / can be considered as overloaded for int and float types.
Having said all the above, these are all language implemented features. Developers cannot custom
overload an operator. So answer for the question, “does Java supports operator overloading?” is “yes
and no”.
OOP In Java Page 34
35. Java wholeheartedly supports function overloading. We can have same function name with different
argument type list.
In inheritance, the ability to replace an inherited method in the subclass by providing a different
implementation is overriding.
Polymorphism is a larger concept which consists of all these different types. So it is not right to say
that overloading or overriding alone is polymorphism. It is more than that.
Coercion Polymorphism
Implicit type conversion is called coercion polymorphism. Assume that we have a function with
argument int. If we call that function by passing a float value and if the the run-time is able to convert
the type and use it accordingly then it is coercion polymorphism.
Now with this definition, let us see if Java has coercion polymorphism. The answer is half yes. Java
supports widening type conversion and not narrowing conversions.
Narrowing Conversion
class FToC {
public static float fToC (int fahrenheit) {
return (fahrenheit - 32)*5/9;
}
public static void main(String args[]) {
System.out.println(fToC(98.4));
}
}
OOP In Java Page 35
36. Java does not support narrowing conversion and we will get error as "FToC.java:7: fToC(int) in FToC
cannot be applied to (double)"
Widening Conversion
class FToC {
public static float fToC (float fahrenheit) {
return (fahrenheit - 32)*5/9;
}
public static void main(String args[]) {
System.out.println(fToC(98));
}
}
The above code will work without an error in Java. We are passing an int value ’98’ wherein the
expected value type is a float. Java implicitly converts int value to float and it supports widening
conversion.
OOP In Java Page 36
37. Universal Polymorphism
Universal polymorphism is the ability to handle types universally. There will be a common template
structure available for operations definition irrespective of the types. Universal polymorphism is
categorized into inclusion polymorphism and parametric polymorphism.
Inclusion polymorphism (subtype polymorphism)
Substitutability was introduced by eminent Barbara Liskov and Jeannette Wing. It is also called as
Liskov substitution principle.
“Let T be a super type and S be its subtype (parent and child class). Then, instances (objects) of T can
be substituted with instances of S.”
Replacing the supertype’s instance with a subtype’s instance. This is called inclusion polymorphism or
subtype polymorphism. This is covariant type and the reverse of it is contravariant. We will discuss the
substitution principle and covariant types, contravariant and invariant earlier in next linked tutorial.
This is demonstrated with a code example. Java supports subtype polymorphism from Java / JDK
version 1.5.
Parametric Polymorphism
Here we go, we have come to ‘Generics’. This is a nice topic and requires a full detailed tutorial with
respect to Java. For now, parametric polymorphism is the ability to define functions and types in a
generic way so that it works based on the parameter passed at runtime. All this is done without
compromising type-safety.
The following source code demonstrates a generics feature of Java. It gives the ability to define a class
and parameterize the type involved. The behavior of the class is based on the parameter type passed
when it is instantiated.
package com.javapapers.java;
OOP In Java Page 37
38. import java.util.ArrayList;
import java.util.List;
public class PapersJar {
private List itemList = new ArrayList();
public void add(T item) {
itemList.add(item);
}
public T get(int index) {
return itemList.get(index);
}
public static void main(String args[]) {
PapersJar papersStr = new PapersJar();
papersStr.add("Lion");
String str = papersStr.get(0);
System.out.println(str);
PapersJar papersInt = new PapersJar();
papersInt.add(new Integer(100));
OOP In Java Page 38
39. Integer integerObj = papersInt.get(0);
System.out.println(integerObj);
}
}
Static Binding vs Dynamic Binding
Give all the above polymorphism types, we can classify these under different two broad groups static
binding and dynamic binding. It is based on when the binding is done with the corresponding values.
If the references are resolved at compile time, then it is static binding and if the references are
resolved at runtime then it is dynamic binding. Static binding and dynamic binding also called as early
binding and late binding. Sometimes they are also referred as static polymorphism and dynamic
polymorphism.
Let us take overloading and overriding for example to understand static and dynamic binding. In the
below code, first call is dynamic binding. Whether to call the obey method of DomesticAnimal or
Animal is resolve at runtime and so it is dynamic binding. In the second call, whether the method
obey() or obey(String i) should be called is decided at compile time and so this is static binding.
package com.javapapers.java;
public class Binding {
public static void main(String args[]) {
Animal animal = new DomesticAnimal();
System.out.println(animal.obey());
DomesticAnimal domesticAnimal = new DomesticAnimal();
OOP In Java Page 39
41. Yes!
Ok!
Advantages of Polymorphism
Generics: Enables generic programming.
Extensibility: Extending an already existing system is made simple.
De-clutters the object interface and simplifies the class blueprint.
OOP In Java Page 40
42. 6) Covariant Return Type in Java
Object oriented programming (OOP) has a principle named substitutability. In this tutorial, let us learn
about substitutability and support for covariant return type in Java. Covariant return type uses the
substitutability principle.
Liskov Substitution Principle
Substitutability was introduced by eminent Barbara Liskov and Jeannette Wing. It is also called as
Liskov substitution principle.
Let T be a super type and S be its subtype (parent and child class). Then, instances (objects) of T can
be substituted with instances of S. Parent’s instances can be replaced with the child’s instances
without change in behavior of the program.
Let WildAnimal be a supertype and Lion be a subtype, then an instance obj1 of WildAnimal can be
replaced by an insance obj2 of Lion
OOP In Java Page 42
43. Covariant, Contravariant and Invariant
The subtyping principle which we discussed above as Liskov principle is called covariant. The reverse
of it (instead of child replacing the parent, the reverse of it as parent replacing the child) is called
contravariant. If no subtyping is allowed then, it is called invariant.
Covariant Type in Java
From the release of JDK 1.5, covariant types were introduced in Java. Following example source code
illustrates the covariant types in java. In the below example, method overriding is used to
demonstrate the covariant type.
In class Zoo, the method getWildAnimal returns ‘WildAnimal’ which is a super type. AfricaZoo extends
Zoo and overrides the method getWildAnimal. While overriding, the return type of this method is
changed from WildAnimal to Lion. This demonstrates covariant type / Liskov substitution principle.
We are replacing the supertype’s (WildAnimal) instance with subtype’s (Lion) instance. This was not
possible before JDK 1.5 IndiaZoo is just another example which demonstrates the same covariant
type.
class WildAnimal {
public String willYouBite(){
return "Yes";
}
}
class Lion extends WildAnimal {
public String whoAreYou() {
OOP In Java Page 43
44. return "Lion";
}
}
class BengalTiger extends WildAnimal {
public String whoAreYou() {
return "Bengal Tiger";
}
}
class Zoo {
WildAnimal getWildAnimal() {
return new WildAnimal();
}
}
class AfricaZoo extends Zoo {
@Override
Lion getWildAnimal() {
return new Lion();
}
}
OOP In Java Page 44
45. class IndiaZoo extends Zoo {
@Override
BengalTiger getWildAnimal() {
return new BengalTiger();
}
}
public class Covariant {
public static void main(String args[]){
AfricaZoo afZoo = new AfricaZoo();
System.out.println(afZoo.getWildAnimal().whoAreYou());
IndiaZoo inZoo = new IndiaZoo();
System.out.println(inZoo.getWildAnimal().whoAreYou());
}
}
OOP In Java Page 45