Polymorphism in Java: – Here Develop A Feature Such that it Takes More than One Form Depending on The Situation. Polymorphism is Applicable Only On Methods. it Can Not be applied On Variable.
Polymorphism in Java
There are Two Ways We Can Access Polymorphism.
- Overriding
- Overloading
Overriding Polymorphism in Java With Example
Overriding: – Here We inherit A Method than We Modify the Logic of the inherited Method of a Child Class by Ones Again Creating A Method in a Child Class With the Same Signature.
Example 1
public class A {
public void test() {
System.out.println(100);
}
}
public class B extends A {
@Override
public void test() {
System.out.println(200);
}
public static void main( String[] args ) {
B b1 = new B();
b1.test();
}
}
Output : 500
You Also Learn –
- What is Abstract Class in Java
- What is Lambda Expression in Java 8
- What is Exception Handling in Java
- Types of Exceptions in Java
- What is inheritance in Java
- What is Final Keyword in Java
- What is Interface in Java
- What is Wrapper Class in Java
- Break Keyword in Java with Example
- What is Method In Java With Example
- What is Constructor in Java With Example
Note 1: Override Annotation Will instruct the Compiler to Check Whether Overring is Happening or not. if Overring does not Happen they will give you an error As shown in Below Example.
public class A {
public void test() {
System.out.println(10);
}
}
public class B extends A{
@Override
public void tests() { // Error
System.out.println(20);
}
public static void main(String[] args) {
B b1 = new B();
b1.test();
}
}
Output : 10
Example 2
public class A {
public void test() {
System.out.println(10);
}
}
public class B extends A{
@Override
public void test() {
System.out.println(20);
}
public static void main(String[] args) {
B b1 = new B();
b1.test();
}
}
Output : 20
Example 3 Overriding
public class GoldAccount {
public void onlineBanking() {
System.out.println("Milega");
}
public void cheqBook() {
System.out.println("nahi Milega");
}
public void rateOfIntrest() {
System.out.println("4%");
}
}
public class PlatinumAccount extends GoldAccount{
@Override
public void cheqBook() {
System.out.println("Free");
}
@Override
public void onlineBanking() {
System.out.println("No");
}
public static void main(String[] args) {
GoldAccount g = new GoldAccount();
g.onlineBanking();
g.cheqBook();
g.rateOfIntrest();
PlatinumAccount p =new PlatinumAccount();
p.onlineBanking();
p.cheqBook();
p.rateOfIntrest();
}
}
Output :
Milega
nahi Milega
4%
No
Free
4%
Overloading Polymorphism in Java With Example
Overloading: – Here We Create A Method With The Same Name in the Same Class More than Ones by giving Different Numbers of Arguments or Different Types of Arguments.
Example 1
public class A {
public void test() {
System.out.println(10);
}
public void test(int x) {
System.out.println(x);
}
public static void main(String[] args) {
A a1 = new A();
a1.test();
a1.test(20);
}
}
Output :
10
20