Polymorphism in Java

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 54

Method signature:

In java, method signature consists of name of the method followed by argument


types.

Example:

Note:

 In java return type is not part of the method signature.


 Compiler will use method signature while resolving method calls.

Ex-:

class Test {
public void m1(double d)
{
}
public void m2(int i)
{
}
public static void main(String ar[]) {
Test t=new Test();
t.m1(10.5);
t.m2(10);
t.m3(10.5); //CE
}
}
Note: - Within the same class we can't take 2 methods with the same signature
otherwise we will get compile time error.

Example:

public void m1()


{
}
public int m1()
{
return 10;
}
Output:
Compile time error
methodOne() is already defined in Test
Polymorphism in Java:-
 Polymorphism in Java is a concept by which we can perform a single action
in different ways. Polymorphism is derived from 2 Greek words: poly and
morphs. The word "poly" means many and "morphs" means forms. So
polymorphism means many forms.
 There are two types of polymorphism in Java: compile-time polymorphism
and runtime polymorphism. We can perform polymorphism in java by
method overloading and method overriding.
 If you overload a static method in Java, it is the example of compile time
polymorphism. Here, we will focus on runtime polymorphism in java.

Note:-

Same name with different forms is the concept of polymorphism.

Example 1: We can use same abs() method for int type, long type, float type etc.

Example:

1. abs(int)

2. abs(long)

3. abs(float)
Types of Polymorphism:-

There are two types of polymorphism in Java:

1. Compile-time polymorphism
2. Runtime polymorphism.

Note: We can perform polymorphism in java by method overloading and method


overriding.

3-Pillars of OOPS:-
1) Inheritance talks about reusability.

2) Polymorphism talks about flexibility.

3) Encapsulation talks about security.


Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.

 Two methods are said to be overload if and only if both having the same
name but different argument types.
 In 'C' language we can't take 2 methods with the same name and different
types.

If there is a change in argument type compulsory we should go for new method


name.

Example:

 Lack of overloading in "C" increases complexity of the programming.


 But in java we can take multiple methods with the same name and different
argument types.
Ex:-

 Having the same name and different argument types is called method
overloading.
 All these methods are considered as overloaded methods.
 Having overloading concept in java reduces complexity of the programming.
 If we have to perform only one operation, having same name of the methods
increases the readability of the program.

Note: - Method overloading is a concept that allows to declare multiple methods


with same name but different parameters in the same class.

Example:

class Test {
public void m1() {
System.out.println("no-arg method");
}
public void m1(int i) {
System.out.println("int-arg method"); //overloaded methods
}
public void m1(double d) {
System.out.println("double-arg method");
}
public static void main(String[] args) {
Test t=new Test();
t.m1();//no-arg method
t.m1(10);//int-arg method
t.m1(10.5);//double-arg method
}
}
Conclusion: In overloading compiler is responsible to perform method resolution
(decision) based on the reference type (but not based on run time object). Hence
overloading is also considered as compile time polymorphism (or) static
polymorphism (or) early biding.

Different ways to overload the method:-

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

Note: - In Java, Method Overloading is not possible by changing the return type of
the method only. Means: If two or more method have same name and same
parameter list but differs in return type can not be overloaded

1) Method Overloading: changing no. of arguments

We have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
Ex:-

We are creating static methods so that we don't need to create instance for calling
methods.

class Adder{
static int add(int a,int b){
return a+b;
}
static int add(int a,int b,int c){
return a+b+c;
}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Output:
22
33
Ex-2:-
class Demo{
void multiply(int l, int b){
System.out.println("Result is"+(l*b)) ;
}
void multiply(int l, int b,int h){
System.out.println("Result is"+(l*b*h));
}
public static void main(String[] args){
Demo ar = new Demo();
ar.multiply(8,5); //multiply(int l, int b) is method is called
ar.multiply(4,6,2); //multiply(int l, int b,int h) is called
}
}
2) Method Overloading: changing data type of arguments

Ex:-

We have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double
arguments.

class Adder{
static int add(int a, int b){
return a+b;
}
static double add(double a, double b){
return a+b;
}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
Output:
22
24.9
Ex-2:-
class Calculate{
void sum (int a, int b){
System.out.println("sum is"+(a+b)) ;
}
void sum (float a, float b){
System.out.println("sum is"+(a+b));
}
Public static void main (String[] args){
Calculate cal = new Calculate();
cal.sum (8,5); //sum(int a, int b) is method is called.
cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
}
}
Output:
Sum is 13
Sum is 8.4
Q) Why Method Overloading is not possible by changing the return type of
method only?

In java, method overloading is not possible by changing the return type of the
method only because of ambiguity. Let's see how ambiguity may occur:
Ex:-
class Adder{
static int add(int a,int b){
return a+b;
}
static double add(int a,int b){
return a+b;
}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}
Output:
Compile Time Error: method add(int,int) is already defined in class Adder

System.out.println(Adder.add(11,11)); //Here, how can java determine which


sum() method should be called?

Can we overload java main() method?

Yes, by method overloading. You can have any number of main methods in a class
by method overloading. But JVM calls main() method which receives string array
as arguments only.
Ex:-

class TestOverloading4{

public static void main(String[] args){

System.out.println("main with String[]");

public static void main(String args){

System.out.println("main with String");

public static void main(){

System.out.println("main without args");

Output:

main with String[]

Ex:-2

public class MethodDemo10{

public static void main(intargs) {

System.out.println("Main Method with int argument Executing");

System.out.println(args);

}
public static void main(char args) {

System.out.println("Main Method with char argument Executing");

System.out.println(args);

public static void main(Double[] args) {

System.out.println("Main Method with Double Executing");

System.out.println(args);

public static void main(String[] args) {

System.out.println("Original main Executing");

MethodDemo10.main(12);

MethodDemo10.main('c');

MethodDemo10.main(1236);

Method overloading if the order of parameters is changed

We can have two methods with same name and parameters but the order of
parameters is different.
Example:

class Demo{

public void get(String name, int id){


System.out.println("Company Name :"+ name);
System.out.println("Company Id :"+ id);
}

public void get(int id, String name){


System.out.println("Company Id :"+ id);
System.out.println("Company Name :"+ name);
}
}

class MethodDemo8{
public static void main (String[] args) {
Demo obj = new Demo();
obj.get("Cherry", 1);
obj.get("Jhon", 2);
}
}
Automatic promotion in overloading.-

 In overloading if compiler is unable to find the method with exact match we


won't get any compile time error immediately.
 1st compiler promotes the argument to the next level and checks whether the
matched method is available or not if it is available then that method will be
considered if it is not available then compiler promotes the argument once
again to the next level. This process will be continued until all possible
promotions still if the matched method is not available then we will get
compile time error. This process is called automatic promotion in
overloading.

byte can be promoted to short, int, long, float or double. The short datatype can be
promoted to int, long, float or double. The char datatype can be promoted to
int,long,float or double and so on.

Method Overloading with TypePromotion:-

class OverloadingCalculation1{
void sum(int a,long b){
System.out.println(a+b);
}

void sum(int a,int b,int c){


System.out.println(a+b+c);
}

public static void main(String args[]){


OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);
}
}
Note: While resolving overloaded methods exact match will always get high
priority
Output:
40
60
Ex-2:-
class Test{
public void methodOne(int i)
{
System.out.println("int-arg method");
}
public void methodOne(float f) //overloaded methods
{
System.out.println("float-arg method");
}
public static void main(String[] args)
{
Test t=new Test();
//t.methodOne('a');//int-arg method
//t.methodOne(10l);//float-arg method
t.methodOne(10.5);//C.E:cannot find symbol
}
}

Method Overloading with Type Promotion if matching found:-

If there are matching type arguments in the method, type promotion is not
performed.

class OverloadingCalculation2{
void sum(int a,int b){
System.out.println("int arg method invoked");
}
void sum(long a,long b){
System.out.println("long arg method invoked");
}

public static void main(String args[]){


OverloadingCalculation2 obj=new OverloadingCalculation2();
obj.sum(20,20);//now int arg sum() method gets invoked
}
}
Output: int arg method invoked
Method Overloading with Type Promotion in case of ambiguity:-
If there are no matching type arguments in the method, and each method promotes
similar number of arguments, there will be ambiguity.

class OverloadingCalculation3{

void sum(int a,long b){

System.out.println("a method invoked");

void sum(long a,int b){

System.out.println("b method invoked");

public static void main(String args[]){

OverloadingCalculation3 obj=new OverloadingCalculation3();

obj.sum(20,20);//now ambiguity

Output:Compile Time Error

Note: One type is not de-promoted implicitly for example double cannot be
depromoted to any type implicitly.

Method overloading and null error


This is a general issue when working with objects, if same name methods having
reference type parameters then be careful while passing arguments.

Below is an example in which you will know how a null value can cause an error
when methods are overloaded.

Example:

Null value is a default value for all the reference types. It created ambiguity to
JVM that reports error.

public class Demo {

public void m1(Integer i) {

System.out.println("test(Integer ) ");

public void m1(String name) {

System.out.println("test(String ) ");

public static void main(String [] args) {

Demo d = new Demo();

d.m1(null);

Output:-
The method test(Integer) is ambiguous for the type Demo

Reason:

The main reason for getting the compile time error in the above example is that
here we have Integer and String as arguments which are not primitive data types in
java and this type of argument do not accept any null value. When the null value is
passed the compiler gets confused which method is to be selected as both the
methods in the above example are accepting null.

However, we can solve this to pass specific reference type rather than value.

Example:

In this example, we are passing specific type argument rather than null value.

public class MethodDemo9 {

public void test(Integer i) {

System.out.println("Method ==> test(Integer)");

public void test(String name) {

System.out.println("Method ==> test(String) ");

public static void main(String [] args) {

MethodDemo9 obj = new MethodDemo9 ();

Integer a = null;

obj.test(a);
String b = null;

obj.test(b);

Ex;-2

class Test
{
public void methodOne(String s)
{
System.out.println("String version");
}
public void methodOne(StringBuffer s)
{
System.out.println("StringBuffer version");
}
public static void main(String[] args)
{
Test t=new Test();
t.methodOne("arun");//String version
t.methodOne(new StringBuffer("sai"));//StringBuffer version
t.methodOne(null);//CE : reference to m1() is ambiquous
}
}
Var- arg methods (variable no of argument methods) (1.5)
 Until 1.4v we can't declared a method with variable no. Of arguments.
 If there is a change in no of arguments compulsory we have to define a new
method.
 This approach increases length of the code and reduces readability.
 But from 1.5 version onwards we can declare a method with variable no. Of
arguments such type of methods are called var-arg methods.

Advantage of Varargs:

 We don't have to provide overloaded methods so less code.

Syntax of varargs:.

We can call or invoke this method by passing any no. Of int values including zero
number also.
Example:

class Test{

public static void m1(int... x){

System.out.println("var-arg method");

public static void main(String[] args){

m1();

m1(10);

m1(10,20,30);

Output:

var-arg method

var-arg method

var-arg method

Ex:-

Class VarargsExample2{

static void display(String... values){

System.out.println("display method invoked ");

for(String s:values){

System.out.println(s);
}

public static void main(String args[]){

display();//zero argument

display("hello");//one argument

display("my","name","is","varargs");//four arguments

Internally var-arg parameter implemented by using single dimensional array hence


within the var-arg method we can differentiate arguments by using index.

Example:

class Test{

public static void sum(int... x){

int total=0;

for(int i=0;i<x.length;i++){

total=total+x[i];

System.out.println("The sum :"+total);

public static void main(String[] args){

sum();
sum(10);

sum(10,20);

sum(10,20,30,40);

Output:

The sum: 0

The sum: 10

The sum: 30

The sum: 100

Example:

class Test{
public static void sum(int... x){
int total=0;
for(int x1 : x){
total=total+x1;
}
System.out.println("The sum :"+total);
}
public static void main(String[] args){
sum();
sum(10);
sum(10,20);
sum(10,20,30,40);
}
}
Output:
The sum: 0
The sum: 10
The sum: 30
The sum: 100
Rules for varargs:
While using the varargs, you must follow some rules otherwise program code won't
compile. The rules are as follows:

 There can be only one variable argument in the method.


 Variable argument (varargs) must be the last argument.

Case-1:-We can mix var-arg parameter with general parameters also.


Example:
M1(int a,int... b) //valid
M1(String s,int... x) //valid
class Demo5
{

public void sum(int a,int... x)//0---any


{
System.out.println("The method executing");
}

public static void main(String[] args){


Demo5 d=new Demo5();
d.sum(10,2,3,4,5,6,7,8,9,0);
}
}
Case 3:
if we mix var-arg parameter with general parameter then var-arg parameter should be
the last parameter.
Example:
M1(int a,int... b) //valid
M1(int... a,int b) //(invalid)
class Demo5
{

public void sum(int... x,int a)//0---any


{
System.out.println("The method executing");
}

public static void main(String[] args){


Demo5 d=new Demo5();
d.sum(10,2,3,4,5,6,7,8,9,0);
}
}
Case 4:
Within the var-arg method we can take only one var-arg parameter. i.e., if we are
trying to more than one var-arg parameter we will get CE.
M1(int... a,int... b) //(invalid)
class Demo5
{

public void sum(int... a,int... x)//0---any


{
System.out.println("The method executing");
}

public static void main(String[] args){


Demo5 d=new Demo5();
d.sum(10,2,3,4,5,6,7,8,9,0);
}
}
Case-5:-
In general var-arg method will get least priority that is if no other method matched
then only var-arg method will get the chance this is exactly same as default case
inside a switch.
class Test{
public static void m1(int i){
System.out.println("general method");
}
public static void m1(int... i)
{
System.out.println("var-arg method");
}
public static void main(String[] args)
{
M1();//var-arg method
M1(10,20);//var-arg method
M1(10);//general method
}
Case 6:
For the var-arg methods we can provide the corresponding type array as argument.
Example:
class Test{
Public static void m1(int…a){
System.out.println("var-arg method");
}
public static void main(String[] args){
methodOne(new int[]{10,20,30});//var-arg method
}
}

Method Overriding in Java:-

 Whatever the Parent has by default available to the Child through


inheritance, if the Child is not satisfied with Parent class method
implementation then Child is allow to redefine that Parent class method in
Child class in its own way this process is called overriding.
Note: If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java.
If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding
 The Parent class method which is overridden is called overridden method.
 The Child class method which is overriding is called overriding method.

Ex:-

class Parent {
public void property(){
System.out.println("cash+land+gold");
}
public void marry() {
System.out.println("Laxmi"); //overridden method
}
}
class Child extends Parent{ //overriding
public void marry() {
System.out.println("Kruthi/keerthi/Kajal/Pooja"); //overriding method
}
}
class Test {
public static void main(String[] args) {
Parent p=new Parent();
p.marry();//laxmi(parent method)
Child c=new Child();
c.marry();//Kruthi/keerthi/Kajal/Pooja (child method)
Parent p1=new Child();
p1.marry();//Kruthi/keerthi/Kajal/Pooja (child method)
}
}
Note: In overriding method resolution is always takes care by JVM based on
runtime object hence overriding is also considered as runtime polymorphism or
dynamic polymorphism or late binding.

The process of overriding method resolution is also known as dynamic method


dispatch.

Note: In overriding runtime object will play the role and reference type is dummy.

Usage of Java Method Overriding:-

 Method overriding is used to provide the specific implementation of a


method which is already provided by its superclass.
 Method overriding is used for runtime polymorphism.

Rules for Java Method Overriding:-

1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Ex:- Understanding the problem without method overriding

class Vehicle{
void run(){
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}
}
Output:
Vehicle is running
Problem is that I have to provide a specific implementation of run() method
in subclass that is why we use method overriding.
Example of with method overriding:-
We have defined the run method in the subclass as defined in the parent class but it
has some specific implementation. The name and parameter of the method are the
same, and there is IS-A relationship between the classes, so there is method
overriding.

Ex:-

class Vehicle{
//defining a method
void run(){
System.out.println("Vehicle is running");
}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){
System.out.println("Bike is running safely");
}
public static void main(String args[]){
Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}
Output:
Bike is running safely

A real example of Java Method Overriding:-


Consider a scenario where Bank is a class that provides functionality to get the rate
of interest. However, the rate of interest varies according to banks. For example,
SBI, ICICI and AXIS banks could provide 8%, 7%, and 9% rate of interest.

Ex:-
class Bank{
int getRateOfInterest(){
return 0;
}
}
//Creating child classes.
class SBI extends Bank{
int getRateOfInterest(){
return 8;
}
}

class ICICI extends Bank{


int getRateOfInterest(){
return 7;
}
}
class AXIS extends Bank{
int getRateOfInterest(){
return 9;
}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Note: In overriding method names and arguments must be same. That is method
signature must be same.

4. Until 1.4 version the return types must be same but from 1.5 version onwards
covariant return types are allowed.

Note: Co-variant return type concept is applicable only for object types but not for
primitives.

5. According to this Child class method return type need not be same as Parent
class method return type its Child types also allowed.

6. Access modifier of child method must not restrictive than parent class method.

Note: While overriding we can't reduce the scope of access modifier.


Note: private < default < protected < public

class Parent {

public void m1() { }

class Child extends Parent {

protected void m1( ) { }

Output:

Compile time error :

Ex:-

/ A Simple Java program to demonstrate


// Overriding and Access-Modifiers

class Parent {
// private methods are not overridden
private void m1()
{
System.out.println("From parent m1()");
}
protected void m2()
{
System.out.println("From parent m2()");
}
}

class Child extends Parent {


// new m1() method
// unique to Child class
private void m1()
{
System.out.println("From child m1()");
}

// overriding method with more accessibility


@Override
public void m2()
{
System.out.println("From child m2()");
}
}

// Driver class
class Main {
public static void main(String[] args)
{
Parent obj1 = new Parent();
obj1.m2();
Parent obj2 = new Child();
obj2.m2();
}
}
Output:
From parent m2()
From child m2()
7. Private, final and static methods cannot be overridden.

Note: Private methods are not visible in the Child classes hence overriding concept
is not applicable for private methods. Based on own requirement we can declare
the same Parent class private method in child class also. It is valid but not
overriding.

Ex: -

class Parent{
Private void m1(){
}
}
Class Child extends Parent{
Private void m1(){
}
}
Note: Parent class final methods we can't override in the Child class.
Note: Parent class non final methods we can override as final in child class. We
can override native methods in the child classes.

Example:

class Parent {
public final void m1() {
}
}
class Child extends Parent{
public void m1(){
}
}
}
Output:
Compile time error:
m1() in Child cannot override m1() in Parent; overridden method is final
Note: We should override Parent class abstract methods in Child classes to provide
implementation.

Example:

abstract class Parent {


public abstract void m1();
}
class Child extends Parent {
public void m1() {
}
}

Note: We can override a non-abstract method as abstract this approach is helpful to


stop availability of Parent method implementation to the next level child classes.

Ex:-

class Parent {

public void m1() {

abstract class Child extends Parent {

public abstract void m1();

Note: Synchronized, strictfp, modifiers won't keep any restrictions on overriding.


Overriding with respect to static methods:

Case 1:

We can't override a static method as non static.

Example:

class Parent{

public static void methodOne(){}

//here static methodOne() method is a class level

class Child extends Parent{

public void methodOne(){}

//here methodOne() method is a object level hence

// we can't override methodOne() method

Output:

CE: methodOne in Child can't override methodOne() in Parent ;

overriden method is static

Case 2:

Similarly we can't override a non static method as static.

Case 3:

class Parent{
public static void methodOne() {}

class Child extends Parent {

public static void methodOne() {}

It is valid. It seems to be overriding concept is applicable for static methods but it


is not overriding it is method hiding.

Static methods can not be overridden(Method Overriding vs Method


Hiding) :

class Parent {
// Static method in base class
// which will be hidden in subclass
static void m1()
{
System.out.println("From parent + "static m1()");
}
// Non-static method which will
// be overridden in derived class
void m2()
{
System.out.println("From parent "+ "non-static(instance) m2()");
}
}
class Child extends Parent {
// This method hides m1() in Parent
static void m1()
{
System.out.println("From child static m1()");
}

// This method overrides m2() in Parent


@Override
public void m2()
{
System.out.println("From child " + "non-static(instance) m2()");
}
}

// Driver class
class Main {
public static void main(String[] args)
{
Parent obj1 = new Child();

// As per overriding rules this


// should call to class Child static
// overridden method. Since static
// method can not be overridden, it
// calls Parent's m1()
obj1.m1();
// Here overriding works
// and Child's m2() is called
obj1.m2();
}
}
Output:
From parent static m1()
From child non-static(instance) m2()

METHOD HIDING:

All rules of method hiding are exactly same as overriding except the following
differences.

Overriding:-

1. Both Parent and Child class methods should be non-static.

2. Method resolution is always takes care by JVM based on runtime object.

3. Overriding is also considered as runtime polymorphism (or) dynamic


polymorphism (or) late binding.

Method hiding:-

1. Both Parent and Child class methods should be static.

2. Method resolution is always takes care by compiler based on reference type.


3. Method hiding is also considered as compile time polymorphism (or) static
polymorphism (or) early biding.

Example:

class Parent {

public static void m1() {

System.out.println("parent class");

class Child extends Parent{

public static void m1(){

System.out.println("child class");

class Test{

public static void main(String[] args) {

Parent p=new Parent();

p.m1();//parent class

Child c=new Child();

c.m1();//child class

Parent p1=new Child();


p1.m1();//parent class

Note: If both Parent and Child class methods are non static then it will become

overriding and method resolution is based on runtime object. In this case the output
is

Parent class

Child class

Child class

Overriding with respect to Var-arg methods:

A var-arg method should be overridden with var-arg method only. If we are trying
to override with normal method then it will become overloading but not overriding.

Example:

class Parent {

public void methodOne(int... i){

System.out.println("parent class");

class Child extends Parent { //overloading but not overriding.

public void methodOne(int i) {

System.out.println("child class");
}

class Test {

public static void main(String[] args) {

Parent p=new Parent();

p.methodOne(10);//parent class

Child c=new Child();

c.methodOne(10);//child class

Parent p1=new Child();

p1.methodOne(10);//parent class

In the above program if we replace child class method with var arg then it will
become overriding. In this case the output is

Parent class

Child class

Child class

Overriding with respect to variables:

Overriding concept is not applicable for variables.

Variable resolution is always takes care by compiler based on reference type.


Example:

class Parent

int x=888;

class Child extends Parent

int x=999;

class Test

public static void main(String[] args)

Parent p=new Parent();

System.out.println(p.x);//888

Child c=new Child();

System.out.println(c.x);//999

Parent p1=new Child();

System.out.println(p1.x);//888

}
}

Note: In the above program Parent and Child class variables, whether both are
static or non static whether one is static and the other one is non static there is no
change in the answer.

Overriding and constructor :

We can not override constructor as parent and child class can never have
constructor with same name(Constructor name must always be same as Class
name).

Difference between method overloading and method overriding in java:-

Method Overloading Method Overridding


Parameter must be different and name Both name and parameter must be
must be same. same.
Compile time polymorphism. Runtime polymorphism.
Increase readability of code. Increase reusability of code.
Access specifier can be changed. Access specifier cannot be more
restrictive than original method(can be
less restrictive).

It is performed within a class It is performed between two classes


using inheritance relation.
It should have methods with the same It should have methods with same
name but a different signature. name and signature.
It can not have the same return type. It should always have the same return
type.
It can be performed using the static It can not be performed using the static
method method
It uses static binding It uses the dynamic binding.

Java Method Overloading example

class OverloadingExample{

static int add(int a,int b){

return a+b;

static int add(int a,int b,int c){

return a+b+c;

Java Method Overriding example

class Animal{

void eat(){

System.out.println("eating bread...");
}

class Dog extends Animal{

void eat(){

System.out.println("eating meat...");

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy