SlideShare a Scribd company logo
1 of 46
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
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
References
1) http://beginnersbook.com/2013/04/oops-concepts/
2) http://javapapers.com/category/java/java-and-oops/
3) http://www.tutorialspoint.com/java/index.htm
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.
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
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
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.
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;
}
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
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
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
}
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
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
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
{
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
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
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
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
}
}
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
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
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.
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.
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
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
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
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
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;
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
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
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 ");
}
}
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
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:
OOP In Java Page 33
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
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
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
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
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
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
System.out.println(domesticAnimal.obey("Ok!"));
}
}
class Animal {
public String obey() {
return "No!";
}
}
class DomesticAnimal extends Animal {
public String obey() {
return "Yes!";
}
public String obey(String i) {
return i;
}
}
Output:
OOP In Java Page 40
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
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
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
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
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
Thank You!

More Related Content

What's hot (20)

Oop java
Oop javaOop java
Oop java
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++
 
XML Document Object Model (DOM)
XML Document Object Model (DOM)XML Document Object Model (DOM)
XML Document Object Model (DOM)
 
polymorphism
polymorphism polymorphism
polymorphism
 
Object-oriented concepts
Object-oriented conceptsObject-oriented concepts
Object-oriented concepts
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
 
String in java
String in javaString in java
String in java
 
Operator overloading and type conversion in cpp
Operator overloading and type conversion in cppOperator overloading and type conversion in cpp
Operator overloading and type conversion in cpp
 
Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2Datatype in c++ unit 3 -topic 2
Datatype in c++ unit 3 -topic 2
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Function overloading(c++)
Function overloading(c++)Function overloading(c++)
Function overloading(c++)
 
07. Virtual Functions
07. Virtual Functions07. Virtual Functions
07. Virtual Functions
 
Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
Js ppt
Js pptJs ppt
Js ppt
 
Function in c
Function in cFunction in c
Function in c
 
Java program structure
Java program structureJava program structure
Java program structure
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
C# operators
C# operatorsC# operators
C# operators
 

Viewers also liked

Practical OOP In Java
Practical OOP In JavaPractical OOP In Java
Practical OOP In Javawiradikusuma
 
Java OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsJava OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsRaja Sekhar
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityVaishali Modi
 
Java buzzwords
Java buzzwordsJava buzzwords
Java buzzwordsramesh517
 
Zulu Embedded Java Introduction
Zulu Embedded Java IntroductionZulu Embedded Java Introduction
Zulu Embedded Java IntroductionAzul Systems Inc.
 
Java OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - SwingJava OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - SwingOUM SAOKOSAL
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCOUM SAOKOSAL
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceOUM SAOKOSAL
 
Android app development - Java Programming for Android
Android app development - Java Programming for AndroidAndroid app development - Java Programming for Android
Android app development - Java Programming for AndroidOUM SAOKOSAL
 
Difference between C++ and Java
Difference between C++ and JavaDifference between C++ and Java
Difference between C++ and JavaAjmal Ak
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01Adil Kakakhel
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programmingSachin Sharma
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingMoutaz Haddara
 
Difference between Java and c#
Difference between Java and c#Difference between Java and c#
Difference between Java and c#Sagar Pednekar
 

Viewers also liked (18)

Practical OOP In Java
Practical OOP In JavaPractical OOP In Java
Practical OOP In Java
 
Java OOP s concepts and buzzwords
Java OOP s concepts and buzzwordsJava OOP s concepts and buzzwords
Java OOP s concepts and buzzwords
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Java buzzwords
Java buzzwordsJava buzzwords
Java buzzwords
 
Zulu Embedded Java Introduction
Zulu Embedded Java IntroductionZulu Embedded Java Introduction
Zulu Embedded Java Introduction
 
Java OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - SwingJava OOP Programming language (Part 7) - Swing
Java OOP Programming language (Part 7) - Swing
 
Introduction to java and oop
Introduction to java and oopIntroduction to java and oop
Introduction to java and oop
 
Java OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBCJava OOP Programming language (Part 8) - Java Database JDBC
Java OOP Programming language (Part 8) - Java Database JDBC
 
Java OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & InterfaceJava OOP Programming language (Part 6) - Abstract Class & Interface
Java OOP Programming language (Part 6) - Abstract Class & Interface
 
Android app development - Java Programming for Android
Android app development - Java Programming for AndroidAndroid app development - Java Programming for Android
Android app development - Java Programming for Android
 
Difference between C++ and Java
Difference between C++ and JavaDifference between C++ and Java
Difference between C++ and Java
 
OOP in Java
OOP in JavaOOP in Java
OOP in Java
 
Java vs. C/C++
Java vs. C/C++Java vs. C/C++
Java vs. C/C++
 
Object oriented programming (oop) cs304 power point slides lecture 01
Object oriented programming (oop)   cs304 power point slides lecture 01Object oriented programming (oop)   cs304 power point slides lecture 01
Object oriented programming (oop) cs304 power point slides lecture 01
 
C++vs java
C++vs javaC++vs java
C++vs java
 
Basic concepts of object oriented programming
Basic concepts of object oriented programmingBasic concepts of object oriented programming
Basic concepts of object oriented programming
 
Introduction to Object Oriented Programming
Introduction to Object Oriented ProgrammingIntroduction to Object Oriented Programming
Introduction to Object Oriented Programming
 
Difference between Java and c#
Difference between Java and c#Difference between Java and c#
Difference between Java and c#
 

Similar to Object+oriented+programming+in+java

Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Ayes Chinmay
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxkristinatemen
 
Java OOPS Concept
Java OOPS ConceptJava OOPS Concept
Java OOPS ConceptRicha Gupta
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdfvenud11
 
Nitish Chaulagai Java1.pptx
Nitish Chaulagai Java1.pptxNitish Chaulagai Java1.pptx
Nitish Chaulagai Java1.pptxNitishChaulagai
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfbca23189c
 
Principles of Object Oriented Programming
Principles of Object Oriented ProgrammingPrinciples of Object Oriented Programming
Principles of Object Oriented ProgrammingKasun Ranga Wijeweera
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfnofakeNews
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP conceptsAhmed Farag
 
Shuvrojit Majumder . 25900120006 Object Oriented Programming (PCC-CS 503) ...
Shuvrojit Majumder .  25900120006  Object Oriented Programming (PCC-CS 503)  ...Shuvrojit Majumder .  25900120006  Object Oriented Programming (PCC-CS 503)  ...
Shuvrojit Majumder . 25900120006 Object Oriented Programming (PCC-CS 503) ...ShuvrojitMajumder
 
Oops presentation java
Oops presentation javaOops presentation java
Oops presentation javaJayasankarPR2
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview QuestionsKuntal Bhowmick
 
Java Interview Questions For Freshers
Java Interview Questions For FreshersJava Interview Questions For Freshers
Java Interview Questions For Fresherszynofustechnology
 

Similar to Object+oriented+programming+in+java (20)

Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
Internet and Web Technology (CLASS-15) [JAVA Basics] | NIC/NIELIT Web Technol...
 
ITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptxITTutor Advanced Java (1).pptx
ITTutor Advanced Java (1).pptx
 
Java OOPS Concept
Java OOPS ConceptJava OOPS Concept
Java OOPS Concept
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
 
Nitish Chaulagai Java1.pptx
Nitish Chaulagai Java1.pptxNitish Chaulagai Java1.pptx
Nitish Chaulagai Java1.pptx
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
 
Principles of Object Oriented Programming
Principles of Object Oriented ProgrammingPrinciples of Object Oriented Programming
Principles of Object Oriented Programming
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
 
javaopps concepts
javaopps conceptsjavaopps concepts
javaopps concepts
 
JAVA-PPT'S.pdf
JAVA-PPT'S.pdfJAVA-PPT'S.pdf
JAVA-PPT'S.pdf
 
Shuvrojit Majumder . 25900120006 Object Oriented Programming (PCC-CS 503) ...
Shuvrojit Majumder .  25900120006  Object Oriented Programming (PCC-CS 503)  ...Shuvrojit Majumder .  25900120006  Object Oriented Programming (PCC-CS 503)  ...
Shuvrojit Majumder . 25900120006 Object Oriented Programming (PCC-CS 503) ...
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
 
Suga java training_with_footer
Suga java training_with_footerSuga java training_with_footer
Suga java training_with_footer
 
Oops presentation java
Oops presentation javaOops presentation java
Oops presentation java
 
Unit 1 Java
Unit 1 JavaUnit 1 Java
Unit 1 Java
 
Java 06
Java 06Java 06
Java 06
 
Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
 
Java Interview Questions For Freshers
Java Interview Questions For FreshersJava Interview Questions For Freshers
Java Interview Questions For Freshers
 

More from Ye Win

001 public speaking
001 public speaking001 public speaking
001 public speakingYe Win
 
My ridiculous productivity secret (i'm using it now)
My ridiculous productivity secret (i'm using it now)My ridiculous productivity secret (i'm using it now)
My ridiculous productivity secret (i'm using it now)Ye Win
 
Mastering google search (i'm using it now)
Mastering google search (i'm using it now)Mastering google search (i'm using it now)
Mastering google search (i'm using it now)Ye Win
 
Java Static Factory Methods
Java Static Factory MethodsJava Static Factory Methods
Java Static Factory MethodsYe Win
 
Avoid creating unncessary objects
Avoid creating unncessary objectsAvoid creating unncessary objects
Avoid creating unncessary objectsYe Win
 
11 rules for programmer should live by
11 rules for programmer should live by11 rules for programmer should live by
11 rules for programmer should live byYe Win
 
Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction ManagementYe Win
 

More from Ye Win (7)

001 public speaking
001 public speaking001 public speaking
001 public speaking
 
My ridiculous productivity secret (i'm using it now)
My ridiculous productivity secret (i'm using it now)My ridiculous productivity secret (i'm using it now)
My ridiculous productivity secret (i'm using it now)
 
Mastering google search (i'm using it now)
Mastering google search (i'm using it now)Mastering google search (i'm using it now)
Mastering google search (i'm using it now)
 
Java Static Factory Methods
Java Static Factory MethodsJava Static Factory Methods
Java Static Factory Methods
 
Avoid creating unncessary objects
Avoid creating unncessary objectsAvoid creating unncessary objects
Avoid creating unncessary objects
 
11 rules for programmer should live by
11 rules for programmer should live by11 rules for programmer should live by
11 rules for programmer should live by
 
Spring Transaction Management
Spring Transaction ManagementSpring Transaction Management
Spring Transaction Management
 

Recently uploaded

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDropbox
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Victor Rentea
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 

Recently uploaded (20)

Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

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:
  • 33. OOP In Java Page 33
  • 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
  • 40. System.out.println(domesticAnimal.obey("Ok!")); } } class Animal { public String obey() { return "No!"; } } class DomesticAnimal extends Animal { public String obey() { return "Yes!"; } public String obey(String i) { return i; } } Output: OOP In Java Page 40
  • 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