Skip to main content

JAVA-OOPS: POLYMORPHISM

This post covers the topic Polymorphism

POLYMORPHISM

  • Poly->many
  • Morphism->forms
  • Taking more than one forms is called polymorphism or one task completed by many ways
It has 2 types,
  1. Method overloading (static binding/compile time polymorphism)
  2. Method overriding (dynamic binding/run time polymorphism)

1. Method overloading:

  • Class->same
  • Method->same
  • Argument->differ
  • In a same class method name is same and the argument is different is called method overloading
  • the argument is depends on
    • data types
    • data types count
    • data type order

Example Program:

public class StudentInfo {
    private void studentId(int num) {
    }
    private void studentId(String name) {     \\ depends on order
    }
    private void studentId(String email, int ph) {     \\depends on data type
    }
    private void studentId(int dob, String add) {     \\depends on datatype count
    }
    public static void main(String[] arg) {
        StudentInfo info = new StudentInfo();
    }
}

  • In the same method the argument can't use int and byte because int & byte both are numbers. so it doesn't work.
  • public void employeeID(int num, byte num2) is not correct

2. Method overriding:

  • Class name->differ(using extends)
  • Method->same
  • Argument->same
  • In a different class , the method name should be same and argument name should be same is called overriding

Example Program:

  • 1st class(sub class)
public class Boy extends Marriage {
    public void girlName() {
        System.out.println("ramya");
    }
    public static void main(String[] args) {
    Boy.b=new Boy();
    b.girlName();
}
  • 2nd class(super class)
public class Marriage {
    public void girlName() {
        System.out.println("priya");
}
output : ramya;
  • The same method name in both class it take sub class only
  • If we satisfied with super class we go for super class method but we won't satisfy with super class we go for sub class method
  • We can assign our sub class to our super class but can't reverse

Example Program:

  • Marriage b=new Boy() is possible
  • Boy b=new Marriage() impossible
  • Inside the class if we use static we don't want to crate object (i.e)
public class Employee{
    public static void addNum(){
        System.out.println("Hello");
    }
    public static void main(String[] args){
    addNum(); // don't want to create object
    }
}
Output: Hello
  • If its different class we have to use class name(i.e)
sub class:
public class Employee{
    public static void addNum(){
        system.out.println("Hello");
   }
}
super class:
public class sample{
    public static void main(string[] args){
        Employee.addNum();
    }
}
Output: Hello

Comments