Computer >> Computer tutorials >  >> Programming >> Java

Can we Overload or Override static methods in Java?


Static methods, in java can be overloaded. But there is a condition that two methods can’t be overloaded I they are only different because of the keyword ‘static’.

Let us see an example −

Example

public class Demo{
   public static void test(){
      System.out.println("Demo class test function has been called");
   }
   public static void test(int val){
      System.out.println("Demo class test function with parameter has been called");
   }
   public static void main(String args[]){
      System.out.println("In the main class, Demo functions being called");
      Demo.test();
      Demo.test(57);
   }
}

Output

In the main class, Demo functions being called
Demo class test function has been called
Demo class test function with parameter has been called

A class named Demo contains a function named ‘test’ that prints a specific message. It also defines another function named ‘test’ with an integer value as a parameter. Relevant message is shown inside the function body. In the main function, the test function is called without parameter and with an integer parameter. Relevant message is displayed on the console.

Static methods, in Java can’t be overridden. Static methods with same signature can be defined in sub-class, but it won’t be runtime polymorphism. Hence, overriding is not possible. Here’s an example −

Example

class base_class{
   public static void show(){
      System.out.println("Static or class method from the base class");
   }
   public void print_it(){
      System.out.println("Non-static or an instance method from the base class");
   }
}
class derived_class extends base_class{
   public static void show(){
      System.out.println("Static or class method from the derived class");
   }
   public void print_it(){
      System.out.println("Non-static or an instance method from the derived class");
   }
}
public class Demo{
   public static void main(String args[]){
      base_class my_instance = new derived_class();
      System.out.println("Base class instance created.");
      my_instance.show();
      System.out.println("Function show called");
      my_instance.print_it();
      System.out.println("Function print_it called");
   }
}

Output

Base class instance created.
Static or class method from the base class
Function show called
Non-static or an instance method from the derived class
Function print_it called

The base class has a static function named ‘show’ that prints a message. Similarly, another function named ‘print_it’ displays a message. A class is derived from the base class that inherits the two functions. A class named Demo contains the main function that creates an instance of base class that is of derived type class. Relevant messages are displayed on the console.