Wednesday, 18 November 2015

Method Overloading

Method Overloading :  

Method Overloading is a feature in Java that allows a class to have two or more methods with the same name but different parameter lists (different number of parameters, different types of parameters, or a different sequence of parameter types).

It is similar to constructor overloading, where a class can have multiple constructors with different argument lists.

Ways to Achieve Method Overloading

Method overloading in Java can be done in three ways:

  1. By changing the number of parameters
  2. By changing the data types of parameters
  3. By changing the sequence of parameter data types

1.By Changing the Number of Parameters :
    
package com.tutorial4u;
class Addition {
       public void sum(int a, int b) {
             int sum = a+b;
             System.out.println("sum of a and b :"+sum);
       }
       public void sum(int a , int b, int c) {
             int sum = a+b+c;
             System.out.println("sum of a, b, and c : "+sum);
       }
}
public class OverloadingExample {
       public static void main(String[] args) {
             Addition add = new Addition();
             add.sum(10, 20);
             add.sum(10, 20, 30);
       }
}
    
Output : 
Sum of a and b : 30
Sum of a, b, and c : 60
2. By Changing the Data Types of Parameters

package com.tutorial4u;
class Addition {
       public void sum(int a, int b) {
             int sum = a+b;
             System.out.println("sum of a and b :"+sum);
       }
       public void sum(double a , double b) {
             double sum = a+b;
             System.out.println("sum of a, b, and c : "+sum);
       }
}
public class OverloadingExample {
       public static void main(String[] args) {
             Addition add = new Addition();
             add.sum(10, 20);
             add.sum(10.5, 20.5);
       }
}

Output : 
Sum of a and b : 30
Sum of a, b, and c : 31.0

3.By Changing the Sequence of Data Types

package com.tutorial4u;
class Tutorial {
       public void display(int a, char c) {
             System.out.println("I am the first definition of method");
       }
       public void display(char c , int b) {
             System.out.println("I am the second definition of method");
       }
}
public class OverloadingExample {
       public static void main(String[] args) {
             Tutorial add = new Tutorial();
             add.display(10, 'a');
             add.display('b', 20);
       }
}
Output : 
I am the first definition of method
I am the second definition of method

Special Cases in Method Overloading :

Case 1: what happen when method signature is same but return type is different ?

package com.tutorial4u;
class Addition {
       public int sum(int a, int b) {
             int sum = a+b;
             return sum;
       }
       public double sum(int a , int b) {// Error!
             double sum = a+b;
              return sum;
       }
}
public class OverloadingExample {
       public static void main(String[] args) {
             Addition add = new Addition();
             add.sum(10, 20);
             add.sum(10, 20);
       }
}

Answer : It will through a compilation error
Duplicate method sum(int, int) in type Addition
Note :👉 Java does not allow method overloading only by changing the return type.

Case 2:  Can we overload java main() method?

Answer : Yes. We can overload the main method any number of times.However, the JVM always calls the main(String[] args) method to start program execution. 

Example : 

class OverloadingExample{ 
  public static void main(String[] args){
       System.out.println("method 1");
       } 
  public static void main(String args){
         System.out.println("method2");
         } 
  public static void main(){
         System.out.println("method3");
        } 
}

Output : 
method 1

Important Points about Method Overloading :

  • Java does not allow overloading by just changing the return type.
  • Private methods can be overloaded.
  • Final methods can be overloaded.
  • Static methods can be overloaded.
  • The main() method can also be overloaded, but the JVM always looks for main(String[] args).

Friday, 16 October 2015

Overriding Method

What is Method Overriding?

Method Overriding in Java occurs when a subclass provides a specific implementation of a method that is already defined in its superclass, using the same method name and same parameter list (method signature).

  • It is used to achieve runtime polymorphism.
  • It allows a subclass to provide its own implementation of an inherited method without modifying the parent class code.

Rules for Method Overriding :
  1. Method Name → Must be the same as the superclass method.

  2. Parameters → Must have the same number and type of parameters.

  3. Access Modifier → Cannot be more restrictive than the superclass method.

    • Restriction order: private ⟹ default ⟹ protected ⟹ public

  4. Return Type → Must be the same or a covariant return type (subclass of the parent’s return type).

  5. Exceptions → Overriding methods can throw unchecked exceptions, but for checked exceptions, the subclass method cannot throw broader or new checked exceptions that the parent method doesn’t declare. Check ðŸ‘‰here in details.

Examples of Method Overriding :

Case 1: By Method Name


package com.tutorial4u;

class Animal{
       public void display() {
             System.out.println("I am a animal.");
       }
}
class Cat extends Animal {
       @Override
       public void display() {
             System.out.println("I am a cat.");
       }
        
}
public class OverridingExample {
       public static void main(String[] args) {
             Animal animal = new Animal();
             animal.display();  //Output : From Super Class
             Cat cat = new Cat();
             cat.display(); //Output : From Sub Class
             Animal animal1 = new Cat();

             animal1.display();// Output from sub class
       }

}

Output :
I am an animal.
I am a cat.
I am a cat.

Case 2: Access Modifier 

(A) Increasing visibility → Allowed

package com.tutorial4u;

class Animal{
       protected void display() {
             System.out.println("I am a animal.");
       }
}
class Cat extends Animal {
       public void display() {
             System.out.println("I am a cat.");
       }
        
}
public class OverridingExample {
       public static void main(String[] args) {
             Animal animal = new Animal();
             animal.display();  //Output : From Super Class
             Cat cat = new Cat();
             cat.display(); //Output : From Sub Class
       }

}

Output

I am an animal.
I am a cat..

(B)Reducing visibility → Compilation Error

package com.tutorial4u;

class Animal{
       protected void display() {
             System.out.println("I am a animal.");
       }
}
class Cat extends Animal {
       //Compilation Error, Cannot reduce the visibility of the inherited method from Animal

       //here visibility must be protected or public but not private or default.
       private void display() {
             System.out.println("I am a cat.");
       }
        
}
public class OverridingExample {
       public static void main(String[] args) {
             Animal animal = new Animal();
             animal.display();  
             Cat cat = new Cat();
             cat.display(); 
       }
}

Note: 👉 The subclass cannot override the method with a more restrictive access modifier.

Output :
Compilation Error, Cannot reduce the visibility of the inherited method from Animal
Case 3: Changing the Number of Parameters (NOT Overriding)

package com.tutorial4u;

class Animal{
       public void display() {
             System.out.println("I am a animal.");
       }
}
class Cat extends Animal {
// This is Overloading, not Overriding
       public void display(int i) {
             System.out.println(i);
       }
        
}
public class OverridingExample {
       public static void main(String[] args) {
             Animal animal = new Animal();
             animal.display();  //Output : From Super Class
             Cat cat = new Cat();
             cat.display(); //Output : From super class
             cat.display(10);
       }
}

Output :

I am an animal.
I am an animal.
10
Note : ðŸ‘‰ Changing the number or type of parameters creates Overloading, not Overriding.

You must not change the arguments of a method in the subclass. If you change the number or types of arguments of the overridden method in the subclass, then it will result in method overloading, not method overriding.

Case 4:  Return Type 
You can only return same type or a subclass of the parents return type , it is known as covariant return type. 

Example : 
package com.tutorial4u;

class A {
}

class B extends A {
}

class Super {
       public A m() {
             System.out.println("Super class method");
             return new A();
       }
}

class Children extends Super {
       public B m() {
             System.out.println("Children class method");
             return new B();
       }
}

public class OverridingExample {
       public static void main(String args[]) {
             Super sup = new Super();
             sup.m();
             Children child = new Children();
             child.m();
       }
}

Output :  
Super class method
Child class method
Special Case: Can We Override Static Methods?
  • No. Static methods cannot be overridden.
  • ✅ A static method in a subclass with the same signature is considered method hiding, not overriding.
No, but we can declare a static method with the same signature in the subclass. It is not considered overriding, as there will be no runtime polymorphism. In this case, the method in the subclass hides the method in the superclass.

Example 1: Static Method Hiding

package com.tutorial4u;

class A {

       public static void m1() {

             System.out.println("method A");

       }

}

class B extends A {

       public static void m1() {

             System.out.println("method B");

       }

}

public class OverridingExample {

       public static void main(String args[]) {

             A a = new B();

             a.m1();

       }

} 


Output : 
method A
Note :  ðŸ‘‰ If m1() was non-static, the output would be "method B" (runtime polymorphism).

Example 2: 

package com.tutorial4u;

class A {

       public static void m1() {

             System.out.println("method a1");

       }

       public void m2() {

             System.out.println("method a2");

       }

}

class B extends A {

       //Compilation Error: This instance method cannot override the static method from A

       public void m1() {

             System.out.println("method b1");

       }

       //Compilation Error: This static method cannot hide the instance method from A

       public static void m2() {

             System.out.println("method b2");

       }

}

public class OverridingExample {

       public static void main(String args[]) {

             A a = new B();

             a.m1();

             a.m2();

       }

}

Output : 

Compilation Error
This instance method cannot override the static method from A
This static method cannot hide the instance method from A

Important Points About Method Overriding

  • Private methods cannot be overridden (not inherited by subclasses).
  • Final methods cannot be overridden(not inherited by subclasses).
  • Static methods cannot be overridden (only hidden).
  • main() method cannot be overridden (because it’s static).
  • An overriding method cannot have a more restrictive access modifier.
  • Only instance methods can be overridden.

Java Development Kit (JDK) and Java Runtime Environment (JRE)

                  Java Development Kit (JDK) and Java Runtime Environment (JRE)  To download and install the Java Development Kit (  JDK ) ...