Можем ли мы перегрузить или переопределить статические методы в java?

Опубликовано: 15 Февраля, 2022

Давайте сначала определим перегрузку и переопределение.
Переопределение: переопределение - это функция языков ООП, таких как Java, которая связана с полиморфизмом времени выполнения. Подкласс (или производный класс) предоставляет конкретную реализацию метода в суперклассе (или базовом классе).
Реализация, которая должна быть выполнена, определяется во время выполнения, и решение принимается в соответствии с объектом, используемым для вызова. Обратите внимание, что сигнатуры обоих методов должны быть одинаковыми. См. Подробности в разделе «Переопределение в Java».
Перегрузка: перегрузка также является особенностью языков ООП, таких как Java, которая связана с полиморфизмом времени компиляции (или статическим). Эта функция позволяет различным методам иметь одно и то же имя, но разные сигнатуры, особенно количество входных параметров и тип входных параметров. Обратите внимание, что как в C ++, так и в Java методы не могут быть перегружены в соответствии с типом возвращаемого значения.

Can we overload static methods? 
The answer is ‘Yes’. We can have two or more static methods with the same name, but differences in input parameters. For example, consider the following Java program. 
 

Java

// filename Test.java
public class Test {
    public static void foo() {
        System.out.println("Test.foo() called ");
    }
    public static void foo(int a) { 
        System.out.println("Test.foo(int) called ");
    }
    public static void main(String args[])
    
        Test.foo();
        Test.foo(10);
    }
}
Output
Test.foo() called 
Test.foo(int) called 

Can we overload methods that differ only by static keyword? 
We cannot overload two methods in Java if they differ only by static keyword (number of parameters and types of parameters is the same). See the following Java program for example. This behavior is the same in C++ (See point 2 of this). 
 

Java

// filename Test.java
public class Test {
    public static void foo() {
        System.out.println("Test.foo() called ");
    }
    public void foo() { // Compiler Error: cannot redefine foo()
        System.out.println("Test.foo(int) called ");
    }
    public static void main(String args[]) { 
        Test.foo();
    }
}

Выход:

Compiler Error, cannot redefine foo()

Can we Override static methods in java? 
We can declare static methods with the same signature in the subclass, but it is not considered overriding as there won’t be any run-time polymorphism. Hence the answer is ‘No’. 
If a derived class defines a static method with the same signature as a static method in the base class, the method in the derived class hides the method in the base class. 
 

Java

/* Java program to show that if static method is redefined by
   a derived class, then it is not overriding. */
  
// Superclass
class Base {
      
    // Static method in base class which will be hidden in subclass 
    public static void display() {
        System.out.println("Static or class method from Base");
    }
      
     // Non-static method which will be overridden in derived class 
     public void print()  {
         System.out.println("Non-static or Instance method from Base");
    }
}
  
// Subclass
class Derived extends Base {
      
    // This method hides display() in Base 
    public static void display() {
         System.out.println("Static or class method from Derived");
    }
      
    // This method overrides print() in Base 
    public void print() {
         System.out.println("Non-static or Instance method from Derived");
   }
}
  
// Driver class
public class Test {
    public static void main(String args[ ])  {
       Base obj1 = new Derived();
         
       // As per overriding rules this should call to class Derive"s static 
       // overridden method. Since static method can not be overridden, it 
       // calls Base"s display() 
       obj1.display();  
         
       // Here overriding works and Derive"s print() is called 
       obj1.print();     
    }
}
Output
Static or class method from Base
Non-static or Instance method from Derived

The following are some important points for method overriding and static methods in Java. 
1) For class (or static) methods, the method according to the type of reference is called, not according to the object being referred, which means method call is decided at compile time.
2) For instance (or non-static) methods, the method is called according to the type of object being referred, not according to the type of reference, which means method calls is decided at run time.
3) An instance method cannot override a static method, and a static method cannot hide an instance method. For example, the following program has two compiler errors. 
 

Java

/* Java program to show that if static methods are redefined by
   a derived class, then it is not overriding but hidding. */
  
// Superclass
class Base {
      
    // Static method in base class which will be hidden in subclass 
    public static void display() {
        System.out.println("Static or class method from Base");
    }
      
     // Non-static method which will be overridden in derived class 
     public void print()  {
         System.out.println("Non-static or Instance method from Base");
    }
}
  
// Subclass
class Derived extends Base {
      
    // Static is removed here (Causes Compiler Error) 
    public void display() {
        System.out.println("Non-static method from Derived");
    }
      
    // Static is added here (Causes Compiler Error) 
    public static void print() {
        System.out.println("Static method from Derived");
   }
}

4) В подклассе (или производном классе) мы можем перегрузить методы, унаследованные от суперкласса. Такие перегруженные методы не скрывают и не переопределяют методы суперкласса - это новые методы, уникальные для подкласса.

Использованная литература:
http://docs.oracle.com/javase/tutorial/java/IandI/override.html
Автор этой статьи Чандра Пракаш. Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше.

Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .