Automation QA Testing Course Content

Showing posts with label Polymorphysm. Show all posts
Showing posts with label Polymorphysm. Show all posts

Polymorphysm Information


Polymorphysm:When one task is performed by different ways i.e. known as polymorphism. For example: to convense the customer differently, to draw something e.g. shape or rectangle etc.

In java, we use method overloading and method overriding to achieve polymorphism.

Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.

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 the static method in java, it is an example of compile-time polymorphism. Here,
 we will focus on runtime polymorphism in java.

Method Overloading:
If a class has multiple methods by the same name but different parameters, it is known as
Method Overloading.

If we have to perform only one operation, having the same name of the methods increases the
 readability of the program.

overloading: The payment option on any eCommerce website has several options like net banking, COD, credit card, etc. That means a payment method is overloaded several times to perform a single payment function in various ways.

Advantage of method overloading?

Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java
By changing the number of arguments
By changing the data type of the parameter
Note: In java, Method Overloading is not possible by changing the return type of the method.
Que) Why Method Overloading is not possible by changing the return type of the method?

In java, method overloading is not possible by changing the return type of the method
because there may occur ambiguity.

Can we overload the main() method?

Yes, by method overloading. You can have any number of main methods in a class by method overloading. Let's see a simple example:

class Overloading1{ 
  public static void main(int a){ 
  System.out.println(a); 
  } 
   
public static void main(String s){
System.out.println(s)

}
  public static void main(String args[]){ 
  System.out.println("main() method invoked"); 
  main(10);
main("java"); 
  } 
} 
QUIZ on Method Overloading:
1)
package polymorph;

public class Test {

public static void main(String[] args) {
print();

}
public static void print(double...a) {
System.out.println("Double");
}

public static void print(int...a) {
System.out.println("Int");
}
}
a)Double
b)Int
c)Exception
-----------------------------------------------------------------------------------------

===========================================================
Method Overriding in Java

If the subclass (child class) has the same method as declared in the parent class, it is known as
 method overriding in java.

In other words, If the subclass provides the specific implementation of the method that has
 been provided by one of its parent classes, it is known as method overriding.

Usage of Java Method Overriding

Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

method must have same name as in the parent class
method must have same parameter as in the parent class.
child class implementation should be different than parent class method.
use inhertitance between classes

Runtime Polymorphism in Java

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass.

 The determination of the method to be called is based on the object being referred to
 by the reference variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

When reference variable of Parent class refers to the object of Child class,
it is known as upcasting. For example:
Parentclass  refvariable=new childclass(); //upcasting
Upcasting in java
must be IS-A relationship (inheritance)

Can we override static method?

No, static method cannot be overridden. It can be proved by runtime polymorphism,
so we will learn it later.


Why we cannot override static method?

because static method is bound with class whereas instance method is bound with object.
Static belongs to class area and instance belongs to heap area.


Can we override java main method?

No, because main is a static method.
-------------------------------------------------------------------------------------------------------
can you override the private method?
Ans)No, because private methods are not accessible in another class.
------------------------------------------------------------------------------------------------------
how can you stop overriding the methods?
Ans)by making private,static and final methods
--------------------------------------------------------------------------------------------------------

overriding: suppose there is a method getInterestRate() which returns the interest rate of a bank. RBI is the superclass and it returns 7 for getInterestRate(). There are various banks like sbi, axis, icici, etc which extend RBI class and override the getInterestRate() method to return 7.5, 8, 8.5, etc respectively.

-------------------------------------------------------------------------------------------------------
Difference between method overloading and method overriding in java
There are many differences between method overloading and method overriding in java. A list of differences between method overloading and method overriding are given below:
No.
Method Overloading
Method Overriding
1)
Method overloading is used to increase the readability of the program.
Method overriding is used to provide the specific implementation of the method that is already provided by its super class.
2)
Method overloading is performed within class.
Method overriding occurs in two classes that have IS-A (inheritance) relationship.
3)
In case of method overloading, parameter must be different.
In case of method overriding, parameter must be same.
4)
Method overloading is the example of compile time polymorphism.
Method overriding is the example of run time polymorphism.
5)
In java, method overloading can't be performed by changing return type of the method only. Return type can be same or different in method overloading. But you must have to change the parameter.
Return type must be same or covariant in method overriding.

=================================================================

Binding in Java

Binding refers to the process of associating a method call with its corresponding method definition. Java has two types of binding:

  1. Static Binding (Early Binding)
  2. Dynamic Binding (Late Binding)

1. Static Binding (Early Binding)

  • Happens at compile-time.
  • Used for private, static, and final methods, as well as instance variables.
  • The method call is resolved based on the reference type (not the object type).
  • Faster because the method is determined at compile-time.

Example of Static Binding:

class Animal {
    static void staticMethod() {
        System.out.println("Animal static method");
    }

    private void privateMethod() {
        System.out.println("Animal private method");
    }

    final void finalMethod() {
        System.out.println("Animal final method");
    }

    void instanceMethod() {
        System.out.println("Animal instance method");
    }
}

class Dog extends Animal {
    static void staticMethod() { // This is method hiding, not overriding
        System.out.println("Dog static method");
    }

    void instanceMethod() { // Overriding method (uses dynamic binding)
        System.out.println("Dog instance method");
    }
}

public class StaticBindingExample {
    public static void main(String[] args) {
        Animal a = new Dog();
        
        // Static methods and final methods are resolved using reference type
        a.staticMethod();  // Calls Animal's static method (Static Binding)
        a.finalMethod();   // Calls Animal's final method (Static Binding)
        
        // Private methods are not inherited, so they are resolved at compile-time.
        // a.privateMethod(); // Compilation error: private method not accessible
        
        // Instance methods are resolved using Dynamic Binding
        a.instanceMethod(); // Calls Dog's overridden method (Dynamic Binding)
    }
}
OUTPUT:
Animal static method
Animal final method
Dog instance method

Key Takeaways from Static Binding:

✔ Static, final, and private methods are bound at compile-time.
✔ Method hiding happens for static methods, not overriding.
✔ Instance variables are also resolved based on reference type (not overridden).


--------------------------------------------------------------------------------------------

2. Dynamic Binding (Late Binding)

  • Happens at runtime.
  • Used for overridden instance methods.
  • The method call is resolved based on the actual object type (not the reference type).
  • Slower than static binding because method resolution happens at runtime.
class Parent {
    void show() {
        System.out.println("Parent show method");
    }
}

class Child extends Parent {
    @Override
    void show() {
        System.out.println("Child show method");
    }
}

public class DynamicBindingExample {
    public static void main(String[] args) {
        Parent p = new Child(); // Upcasting
        p.show(); // Calls Child's overridden method (Dynamic Binding)
    }
}

OUTPUT:
Child show method

Key Takeaways from Dynamic Binding:

✔ Overridden methods are resolved at runtime based on object type.
✔ This enables polymorphism, allowing method calls to be dynamically resolved.
✔ Instance variables are not overridden, only methods are.

Differences Between Static and Dynamic Binding

Feature                            Static Binding (Early)                                   Dynamic Binding (Late)
When it happens             Compile-time                                                    Runtime
Methods involved     static, final, private methods                       Overridden instance methods
Resolution                     Based on reference type                                   Based on object type
Performance                 Faster                                                                   Slower
Polymorphism support No                                                                      Yes
Example                           a.staticMethod();                       a.instanceMethod();

how-method-overriding-works

Hi! You're already using Java methods and know a lot about them. How method overriding works - 1You've probably faced the situation where one class has many methods with the same name but different parameters. You'll recall that in those cases we used method overloading. Today we're considering another situation. Imagine that we have a single shared method, but it must do different things in different classes. How do we implement this behavior? To understand, let's consider an Animal parent class, which represents animals, and we'll create a speak method in it:
public class Animal {

   public void speak() {

       System.out.println("Hello!");
   }
}
Though we've only just started writing the program, you probably see a potential problem: there are a lot of animals in the world, and they all 'speak' differently: cats meow, ducks quack, and snakes hiss. How method overriding works - 2Our goal is simple: avoid creating loads of speaking methods. Instead of creating a catSpeak() method for meowing, a snakeSpeak() method for hissing, etc., we want to call the speak() method and have the snake hiss, the cat meow, and the dog bark. We can easily achieve this using method overriding. Wikipedia gives the following explanation of the term 'overriding': Method overriding, in object-oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes That is essentially correct. Method overriding lets you take some method of the parent class and write your own implementation in each child class. The new implementation 'replaces' the parent's implementation in the child class. Let's see how this looks in an example. Create 4 classes that inherit our Animal class:
public class Bear extends Animal {
   @Override
   public void speak() {
       System.out.println("Growl!");
   }
}
public class Cat extends Animal {

   @Override
   public void speak() {
       System.out.println("Meow!");
   }
}

public class Dog extends Animal {

   @Override
   public void speak() {
       System.out.println("Woof!");
   }
}


public class Snake extends Animal {

   @Override
   public void speak() {
       System.out.println("Hiss!");
   }
}
"Here's a small lifehack for the future: to override the parent class's methods, go to the child class's code in IntelliJ IDE, Click Ctrl+O, and choose "Override methods..." in the menu. Get used to using hot keys from the outset — it will help you write programs faster! To specify the behavior we need, we did a few things:
  1. In each child class, we created a method with the same name as the parent class's method.

  2. We told the compiler that naming the method the same as in the parent class wasn't happenstance: we want to override its behavior. To communicate this to the compiler, we set the @Override annotation above the method.
    When placed above a method, the @Override annotation informs the compiler (as well as programmers reading your code): 'Everything is okay. This isn't a mistake. I'm not being forgetful. I'm aware that such a method already exists and I want to override it'.

  3. We wrote the implementation we need for each child class. When the speak() method is called, a snake should hiss, a bear should growl, etc.
Let's see how this works in a program:
public class Main {

   public static void main(String[] args) {

       Animal animal1 = new Dog();
       Animal animal2 = new Cat();
       Animal animal3 = new Bear();
       Animal animal4 = new Snake();

       animal1.speak();
       animal2.speak();
       animal3.speak();
       animal4.speak();
   }
}
Console output: Woof! Meow! Growl! Hiss! Excellent! Everything works as it should! We created 4 reference variables that store objects of the Animal parent class, and we assigned instances of 4 different child classes to them. As a result, each object exhibits its own behavior. For each child class, the overridden speak() method replaced the 'native' speak() method in the Animal class (which simply displays 'Hello!'). How method overriding works - 3Overriding has several limitations:
  1. The overridden method must have the same parameters as the parent method.
    If the parent class's speak method has a String parameter, the overridden method in the child class must also have a String parameter. Otherwise, the compiler will generate an error:
    public class Animal {
    
       public void speak(String s) {
    
           System.out.println("Hello! " + s);
       }
    }
    
    public class Cat extends Animal {
    
       @Override // Error!
       public void speak() {
           System.out.println("Meow!");
       }
    }

  2. The overridden method must have the same return type as the parent method.
    Otherwise, we'll get a compiler error:
    public class Animal {
    
       public void speak() {
    
           System.out.println("Hello!");
       }
    }
    
    
    public class Cat extends Animal {
    
       @Override
       public String speak() {         // Error!
           System.out.println("Meow!");
           return "Meow!";
       }
    }

  3. The access modifier on the overridden method must also be the same as the 'original' method:
    public class Animal {
    
          public void speak() {
    
                System.out.println("Hello!");
          }
    }
    
    public class Cat extends Animal {
    
           @Override
           private void speak() {      // Error!
               System.out.println("Meow!");
           }
    }
Method overriding in Java is one way to implement polymorphism (the principle of OOP that we described in the last lesson). This means that its main advantage is the same flexibility that we discussed previously. We can build a simple and logical system of classes, each having a specific behavior (dogs bark, cats meow), with a common interface — a single speak() method for them all rather than loads of methods, e.g. dogSpeak(), speakCat(), etc