天天看點

c++多态與java多态性_Java中的多态性

c++多态與java多态性_Java中的多态性

c++多态與java多态性

  • Polymorphism is used to assume the ability of several

    different forms. Or we can say performing one task in different ways.

  • In java + operator is used for addition as well to concatenate

    (join) strings. Here a single operator is doing two different things depending

    upon the type of argument, so it is the situation of polymorphism.

Types of Polymorphism

Compile Time Polymorphism

  • When functionality of an object bound at compile time, it is

    known as compile time polymorphism.

  • Compile time polymorphism is of two types, operator overloading

    and method overloading.

  • Java doesn’t support operator overloading, it only support method overloading.
Note:

It is given in java language specification that java doesn’t

support compile time polymorphism, method overloading is also supported at method overriding.

Runtime Polymorphism

  • When functionality of an object bound at runtime, it is

    known as runtime polymorphism.

  • Method overriding

    is the example of runtime polymorphism.

Method Overloading

Whenever we keep more than one method of same name but

different in prototype in a class, it is known as method overloading. Method overloading is achieved when: 1. Number of arguments are different void show(int a); void show(int a, int b); 2. Number of arguments same but different in data type void show(int a); void show(float a); void show(long a); A program to show method overloading is given below. class demo {   void show(int a)   {    

System.out.println(“int”);   }   void show(float a)   {    

System.out.println(“float”);   }   void show(long a)   {    

System.out.println(“long”);   }   public static void main(String…s)   {     demo d = new

demo();     d.show(10);     d.show(10.0F);     d.show(10L);   } }

Method Overriding

Whenever parent and child class have same method, it is

known as method overriding. class base {                 void

show()                 {                                 System.out.println(“base”);                 } } class child extends base {                 void

show()                 {                                 System.out.println(“child”);                 }                 public

static void main(String…s)                 {                                 child

c=new child();                                 c.show();                 } }

c++多态與java多态性_Java中的多态性

If you have any doubt in above tutorial then you can ask

your question.

翻譯自: https://www.thecrazyprogrammer.com/2014/08/polymorphism-in-java.html

c++多态與java多态性