Java has two types of polymorphism: compile time polymorphism and runtime polymorphism. We can demonstrate polymorphism in Java by method overload and method override.
A reference variable can refer to any object of any subtype of its declared type or its declared type. A reference variable can be declared as a class or interface type.
Polymorphism can be achieved in two of the following ways:
Method Overloading
Compile time polymorphism refers to a process in which an overloaded method is resolved over time at compile time instead of the call. Method overloading is an example of timing polymorphism. Law overloading is a feature that allows a class to have two or more methods with the same name, but the logic passed by the methods is different.
Example -
class Adder {Static int add(int a, int b){return a+b;}static double add( double a, double b){return a+b;}public static void main(String args[]){System.out.println(Adder.add(11,11));System.out.println(Adder.add(12.3,12.6));}}
Method Overriding
Runtime Polymorphism or Dynamic Method Dispatch is a process in which an override method is resolved at runtime instead of compiled-time calls.
Syntax -
class A{}
class B extends A{} .
class B extends A{} .
Example -
public Class BowlerClass{void bowlingMethod(){System.out.println(" bowler ");}public Class FastPacer{void bowlingMethod(){System.out.println(" fast bowler ");}Public static void main(String[] args){FastPacer obj= new FastPacer();obj.bowlingMethod();}}

0 comments:
Post a Comment