Polymorphism in Java – Method Overloading and Overriding

13
Home Find Jobs Free Java eBooks Get in touch Beginner's Book Core Java Interview Questions OOPs Concepts Java Collections JSP JSTL Servlet Web Development SEO WordPress Polymorphism in Java – Method Overloading and Overriding OOPs Concept In the last tutorial we discussed inheritance. Here we will discuss polymorphism, which is one of the feature of Object oriented programming(OOPs). Polymorphism in Java – Method Overloading and... http://beginnersbook.com/2013/03/polymorphism-... 1 of 13 25/01/2015 07:15 ከሰዓት

Transcript of Polymorphism in Java – Method Overloading and Overriding

Page 1: Polymorphism in Java – Method Overloading and Overriding

HomeFind JobsFree Java eBooksGet in touch

Beginner's Book≡

Core Java Interview QuestionsOOPs Concepts Java Collections

JSP JSTL

ServletWeb Development

SEOWordPress

Polymorphism in Java – Method Overloading andOverriding

OOPs Concept

In the last tutorial we discussed inheritance. Here we will discusspolymorphism, which is one of the feature of Object orientedprogramming(OOPs).

Polymorphism in Java – Method Overloading and... http://beginnersbook.com/2013/03/polymorphism-...

1 of 13 25/01/2015 07:15 ከሰዓት

Page 2: 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 theobject that it is acting upon. In other words, polymorphism allows you defineone 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 internalstructures to share the same external interface.Polymorphism is extensively used in implementing inheritance.

Following concepts demonstrate different types of polymorphism in java.1) Method Overloading2) 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.

Polymorphism in Java – Method Overloading and... http://beginnersbook.com/2013/03/polymorphism-...

2 of 13 25/01/2015 07:15 ከሰዓት

Page 3: Polymorphism in Java – Method Overloading and Overriding

1)Method Overloading:In Java, it is possible to define two or more methods of same name in a class,provided that there argument list or parameters are different. This concept isknown as Method Overloading.

I have covered method overloading and Overriding below. To know more aboutpolymorphism types refer my post Types of polymorphism in java: Static,Dynamic, Runtime and Compile time Polymorphism.

1) Method Overloading

To call an overloaded method in Java, it is must to use the type and/ornumber of arguments to determine which version of the overloadedmethod to actually call.

1.

Overloaded methods may have different return types; the return type aloneis insufficient to distinguish two versions of a method. .

2.

When Java encounters a call to an overloaded method, it simply executesthe version of the method whose parameters match the arguments used inthe call.

3.

It allows the user to achieve compile time polymorphism.4. An overloaded method can throw different exceptions.5. It can have different access modifiers.6.

Example:

class Overload{ void demo (int a) { System.out.println ("a: " + a);

Questions &Answers

Online Tests, Quizzes andSurveys On Various Subjects.

Sign Up now!

Polymorphism in Java – Method Overloading and... http://beginnersbook.com/2013/03/polymorphism-...

3 of 13 25/01/2015 07:15 ከሰዓት

Page 4: Polymorphism in Java – Method Overloading and Overriding

}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. Themethods are invoked or called with the same type and number of parametersused.

Output:

a: 10a and b: 10,20double a: 5.5O/P : 30.25

Rules for Method Overloading

Overloading can take place in the same or in its sub-class.1. Constructor in Java can be overloaded2. Overloaded methods must have a different argument list.3. Overloaded method should always be in part of the same class, with samename but different parameters.

4.

The parameters may differ in their type or number, or in both.5. They may have the same or different return types.6. It is also known as compile time polymorphism.7.

2) Method Overriding

Child class has the same method as of base class. In such cases child classoverrides the parent class method without even touching the source code of the

Polymorphism in Java – Method Overloading and... http://beginnersbook.com/2013/03/polymorphism-...

4 of 13 25/01/2015 07:15 ከሰዓት

Page 5: Polymorphism in Java – Method Overloading and Overriding

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 objectBaseClass obj1 = new BaseClass();// BaseClass reference but DerivedClass objectBaseClass obj2 = new DerivedClass();// Calls the method from BaseClass class

obj1.methodToOverride();//Calls the method from DerivedClass class

obj2.methodToOverride();}

}

Output:

I'm the method of BaseClassI'm the method of DerivedClass

Rules for Method Overriding:

applies only to inherited methods1. object type (NOT reference variable type) determines which overriddenmethod will be used at runtime

2.

Overriding methods must have the same return type3. Overriding method must not have more restrictive access modifier4. Abstract methods must be overridden5. Static and final methods cannot be overridden6. Constructors cannot be overridden7. It is also known as Runtime polymorphism.8.

super keyword in Overriding:

Polymorphism in Java – Method Overloading and... http://beginnersbook.com/2013/03/polymorphism-...

5 of 13 25/01/2015 07:15 ከሰዓት

Page 6: Polymorphism in Java – Method Overloading and Overriding

When invoking a superclass version of an overridden method the super keywordis used.Example:

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 methodSystem.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

}}

Output:

Vehicles are used for moving from one place to anotherCar is a good medium of transport

You Might Like:

Difference between method Overloading and Overriding in javaMethod Overloading in Java with examplesTypes of polymorphism in java- Runtime and Compile timepolymorphism

Polymorphism in Java – Method Overloading and... http://beginnersbook.com/2013/03/polymorphism-...

6 of 13 25/01/2015 07:15 ከሰዓት

Page 7: Polymorphism in Java – Method Overloading and Overriding

OOPs in Java- Encapsulation, Inheritance, Polymorphism,AbstractionMethod overriding in java with exampleConstructor Overloading in Java with examplesException handling in Method overriding with example

java OOPs overloading overriding polymorphism

Previous Article Next Article

4 comments… add one

tANGENI October 13, 2014, 7:44 AM

How do you create constructors in a child class, am confused can anybodyhelp please.

Replyjanaki raman m October 15, 2014, 10:12 AM

sir/madami needa java program two types of polymorphism1. compile time method overloading and constructor overloading2. run time method overridingplease urgent

Replyshinam November 9, 2014, 4:30 PM

what is the exact meaning of super keyword.and i want simple program which is basd on super keyword only

ReplyChaitanya Singh November 15, 2014, 8:08 AM

Refer this article: http://beginnersbook.com/2013/04/java-static-class-block-methods-variables/

Reply

Leave a Comment

Name *

Email *

Polymorphism in Java – Method Overloading and... http://beginnersbook.com/2013/03/polymorphism-...

7 of 13 25/01/2015 07:15 ከሰዓት

Page 8: Polymorphism in Java – Method Overloading and Overriding

Website

Comment

Submit

Confirm you are a human Being

Notify me of followup comments via e-mail

OOPs Concepts

Method overloadingMethod overridingOverloading vs OverridingConstructorDefault constructorParameterized constructorPrivate constructorConstructor in interfaceConstructor chainingstatic constructorConstructor overloadingAggregationAssociationOOPs basicsPolymorphismTypes of polymorphismInheritanceTypes of inheritanceHybrid inheritanceHierarchical inheritanceMultilevel inheritanceMultiple inheritanceEncapsulationStatic and dynamic bindingStatic classStatic methodsStatic variables

Polymorphism in Java – Method Overloading and... http://beginnersbook.com/2013/03/polymorphism-...

8 of 13 25/01/2015 07:15 ከሰዓት

Page 9: Polymorphism in Java – Method Overloading and Overriding

Static importStatic constructorInner classesAbstract class and methodsInterfaceAbstract class vs interfaceAccess modifiersPackages

MORE ...

String handlingException handlingMultithreadingJava I/O TutorialJava Serialization

Polymorphism in Java – Method Overloading and... http://beginnersbook.com/2013/03/polymorphism-...

9 of 13 25/01/2015 07:15 ከሰዓት

Page 10: Polymorphism in Java – Method Overloading and Overriding

Join Us On Google Plus

BeginnersBook

+ 1,809

Follow +1

Polymorphism in Java – Method Overloading and... http://beginnersbook.com/2013/03/polymorphism-...

10 of 13 25/01/2015 07:15 ከሰዓት

Page 11: Polymorphism in Java – Method Overloading and Overriding

Follow Me on Google+

Chaitanya Singh

1,065 followers

Follow

Polymorphism in Java – Method Overloading and... http://beginnersbook.com/2013/03/polymorphism-...

11 of 13 25/01/2015 07:15 ከሰዓት

Page 12: Polymorphism in Java – Method Overloading and Overriding

Reference Links

Download JavaEclipse IDE DownloadsJava DocumentationJava EE 5 TutorialJava EE 6 TutorialJava EE 7 TutorialJava SE 6.0 API SpecificationJava SE 7.0 API SpecificationJavaServer Pages - JSP

Popular Tutorials

Core Java TutorialJSP TutorialJSTL TutorialJava Collections Tutorial

Polymorphism in Java – Method Overloading and... http://beginnersbook.com/2013/03/polymorphism-...

12 of 13 25/01/2015 07:15 ከሰዓት

Page 13: Polymorphism in Java – Method Overloading and Overriding

Servlet TutorialC TutorialJava Regular Expressions TutorialJava Enum TutorialJava Annotations Tutorial

Friends & Links

FromDev.comDZone - Fresh Links

Most Visited

Java InterviewServlet InterviewJUnit Interview

About Chaitanya Singh

Founder of beginnersBook.com, loves Java and open source stuff.BeginnersBook.com is a tech blog where he shares tutorials on programming(Java, C, CPP), WordPress, SEO and web development.

Connect on

Copyright © 2012 – 2014 BeginnersBook – All Rights Reserved || Sitemap

Polymorphism in Java – Method Overloading and... http://beginnersbook.com/2013/03/polymorphism-...

13 of 13 25/01/2015 07:15 ከሰዓት