- How to Override/Overload Static Method in Java?
- Function Overloading
- Example
- Function Overriding
- Example
- Can a Static Method be Overridden?
- Example
- Can a Static Method be Overloaded?
- Example
- Can a Static Method be Overloaded from Non-Static Method?
- Example
- Overriding and Hiding Methods
- Static Methods
- Interface Methods
- Modifiers
- Summary
How to Override/Overload Static Method in Java?
Overriding and Overloading is a way to achieve Polymorphism in OOP. It is one of the most common and important questions which is asked in many interview and competitive exams. Let’s understand what is the meaning of these terms overriding, overloading and static method. At the end of this discussion, one will get to know whether function overriding and function overloading is feasible on a static method or not.
Function Overloading
If more than one method of a class (be it in the same class or inherited by another class) have the same name but they differ in their method signatures, then the methods are said to be overloaded. Consider the example given below
Example
class A public void read(int a) System.out.println("I am in class A"); System.out.println(a); > > class B extends A public void read(int a, int b) System.out.println("I am in class B"); System.out.println(a); System.out.println(b); > > public class test public static void main(String[] args) B obj = new B(); obj.read(10); obj.read(20, 30); > >
I am in class A 10 I am in class B 20 30
As we created the object of class B and passed a single argument in the function read , then the method which accepted only a single argument gets executed i.e. method in class A but when we passed two arguments in the read method then the method in class B gets executed as it accepts two arguments in its parameters.
It is decided at the compile-time only by the compiler that which method is going to be executed according to the number of arguments that are being passed to a method. Hence overloading is used to implement compile-time polymorphism.
Function Overriding
If two or more methods which have the same name and same method signature are declared in different classes to implement some specific feature then we say that those methods are overridden. Overriding is used for implementing run-time polymorphism. Understand this with the given example
Example
class A public void read(int a) System.out.println("I am in class A"); System.out.println(a); > > class B extends A public void read(int a) System.out.println("I am in class B"); System.out.println(a); > > public class test public static void main(String[] args) B obj = new B(); obj.read(10); > >
Since class B extends class A and the read method of class A is available to it, still the preference is given to the read method that is present in class B and is executed. Here the method read in class A has been overridden by class B .
It is decided at the runtime that which function is going to be executed according to the object that is being created for calling the methods. If the object of the parent class is being used for calling, then the read method of the parent class is executed and if the object of child class is being used for calling, then the read method of child class gets executed.
Can a Static Method be Overridden?
The answer is NO. We cannot override a static method in Java. Understand this with the help of an example given below
Example
class car public static void start() System.out.println("Car starts"); > public void stop() System.out.println("Car stops"); > public void refuel() System.out.println("Car refuels"); > > public class honda extends car public static void start() System.out.println("Honda starts"); > > public class test public static void main(String[] args) honda h = new honda(); h.start(); h.stop(); h.refuel(); > >
Honda starts Car stops Car refuels
If you try to access the h.start() function, first it will give a warning because the static method will be stored at a common memory allocation in java memory and if we try to access the h.start() with object reference type it will give us a warning because the static method will never be stored inside the object. Hence it is preferred to call a static method with the help of class rather than calling it with an object. The above code will give the output Honda starts i.e. h.start() function of child class will be executed because we called the function with the help of the object of class B . If we would have called it with the help of the object of class A then start function of class A would have been executed.
Static methods are stored at a common memory allocation in Java memory and if we try to access the h.start() , which is basically a static function, with object reference type it will give us a warning because the static methods are never stored inside the object. Hence it is preferred to call a static method with the help of class rather than calling it with an object.
The above code will give the output Honda starts i.e. h.start() function of child class will be executed because we called the function with the help of the object of class honda . If we would have called it with the help of the object of class car then start function of class car would have been executed.
- We cannot access the start function of the class car (parent class) with the help of the class honda (child class). It is called method hiding in Java i.e. static function start in class car is hidden.
- A static method cannot be overridden by a non-static method and a non-static method cannot be hidden by a static method.
- Hence it depends on the type of reference variable used for calling static methods, therefore static methods are decidable at the compile time. Hence, they cannot be overridden.
Can a Static Method be Overloaded?
Now we know that a static function cannot be overridden but what about overloading? The answer is YES. Static methods can be overloaded in Java without any errors. For example
Example
class A public static void read(int a) System.out.println("I am in class A"); System.out.println(a); > > class B extends A public static void read(int a, int b) System.out.println("I am in class B"); System.out.println(a); System.out.println(b); > > public class test public static void main(String[] args) B obj = new B(); obj.read(10); obj.read(20, 30); > >
I am in class A 10 I am in class B 20 30
The above code gets executed without any error and hence we can say that static methods can be overloaded.
Can a Static Method be Overloaded from Non-Static Method?
The answer is NO. The compiler will raise an error if we try to overload a static function which differs only in the static keyword. Consider the below example
Example
class A public void read(int a) System.out.println("I am in class A"); System.out.println(a); > public static void read(int a) System.out.println("I am in class B"); System.out.println(a); > public static void main(String[] args) A.read(10); > >
error: method read(int) is already defined in class A error: non-static method read(int) cannot be referenced from a static context
The above code will show an error at the time of compilation which shows that the static method which differs only in static keyword is not overloaded.
With this, we end our topic and we hope that the concept of overriding and overloading with static methods is clear to you.
Help us improve this content by editing this page on GitHub
Overriding and Hiding Methods
An instance method in a subclass with the same signature (name, plus the number and the type of its parameters) and return type as an instance method in the superclass overrides the superclass’s method.
The ability of a subclass to override a method allows a class to inherit from a superclass whose behavior is «close enough» and then to modify behavior as needed. The overriding method has the same name, number and type of parameters, and return type as the method that it overrides. An overriding method can also return a subtype of the type returned by the overridden method. This subtype is called a covariant return type.
When overriding a method, you might want to use the @Override annotation that instructs the compiler that you intend to override a method in the superclass. If, for some reason, the compiler detects that the method does not exist in one of the superclasses, then it will generate an error. For more information on @Override , see Annotations .
Static Methods
If a subclass defines a static method with the same signature as a static method in the superclass, then the method in the subclass hides the one in the superclass.
The distinction between hiding a static method and overriding an instance method has important implications:
- The version of the overridden instance method that gets invoked is the one in the subclass.
- The version of the hidden static method that gets invoked depends on whether it is invoked from the superclass or the subclass.
Consider an example that contains two classes. The first is Animal , which contains one instance method and one static method:
public class Animal < public static void testClassMethod() < System.out.println("The static method in Animal"); >public void testInstanceMethod() < System.out.println("The instance method in Animal"); >>
The second class, a subclass of Animal , is called Cat :
public class Cat extends Animal < public static void testClassMethod() < System.out.println("The static method in Cat"); >public void testInstanceMethod() < System.out.println("The instance method in Cat"); >public static void main(String[] args) < Cat myCat = new Cat(); Animal myAnimal = myCat; Animal.testClassMethod(); myAnimal.testInstanceMethod(); >>
The Cat class overrides the instance method in Animal and hides the static method in Animal . The main method in this class creates an instance of Cat and invokes testClassMethod() on the class and testInstanceMethod() on the instance.
The output from this program is as follows:
The static method in Animal The instance method in Cat
As promised, the version of the hidden static method that gets invoked is the one in the superclass, and the version of the overridden instance method that gets invoked is the one in the subclass.
Interface Methods
Default methods and abstract methods in interfaces are inherited like instance methods. However, when the supertypes of a class or interface provide multiple default methods with the same signature, the Java compiler follows inheritance rules to resolve the name conflict. These rules are driven by the following two principles:
- Instance methods are preferred over interface default methods. Consider the following classes and interfaces:
public interface Mythical < default public String identifyMyself() < return "I am a mythical creature."; >>
public class Pegasus extends Horse implements Flyer, Mythical < public static void main(String. args) < Pegasus myApp = new Pegasus(); System.out.println(myApp.identifyMyself()); >>
public interface EggLayer extends Animal < default public String identifyMyself() < return "I am able to lay eggs."; >>
public interface FireBreather extends Animal
public class Dragon implements EggLayer, FireBreather < public static void main (String. args) < Dragon myApp = new Dragon(); System.out.println(myApp.identifyMyself()); >>
If two or more independently defined default methods conflict, or a default method conflicts with an abstract method, then the Java compiler produces a compiler error. You must explicitly override the supertype methods.
Consider the example about computer-controlled cars that can now fly. You have two interfaces ( OperateCar and FlyCar ) that provide default implementations for the same method, ( startEngine ):
public interface OperateCar < // . default public int startEngine(EncryptedKey key) < // Implementation >>
A class that implements both OperateCar and FlyCar must override the method startEngine . You could invoke any of the of the default implementations with the super keyword.
public class FlyingCar implements OperateCar, FlyCar < // . public int startEngine(EncryptedKey key) < FlyCar.super.startEngine(key); OperateCar.super.startEngine(key); >>
The name preceding super (in this example, FlyCar or OperateCar ) must refer to a direct superinterface that defines or inherits a default for the invoked method. This form of method invocation is not restricted to differentiating between multiple implemented interfaces that contain default methods with the same signature. You can use the super keyword to invoke a default method in both classes and interfaces.
Inherited instance methods from classes can override abstract interface methods. Consider the following interfaces and classes:
public class Mustang extends Horse implements Mammal < public static void main(String. args) < Mustang myApp = new Mustang(); System.out.println(myApp.identifyMyself()); >>
The method Mustang.identifyMyself returns the string I am a horse. The class Mustang inherits the method identifyMyself from the class Horse , which overrides the abstract method of the same name in the interface Mammal .
Note: Static methods in interfaces are never inherited.
Modifiers
The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.
You will get a compile-time error if you attempt to change an instance method in the superclass to a static method in the subclass, and vice versa.
Summary
The following table summarizes what happens when you define a method with the same signature as a method in a superclass.
Superclass Instance Method | Superclass Static Method | |
---|---|---|
Subclass Instance Method | Overrides | Generates a compile-time error |
Subclass Static Method | Generates a compile-time error | Hides |
Note: In a subclass, you can overload the methods inherited from the superclass. Such overloaded methods neither hide nor override the superclass instance methodsthey are new methods, unique to the subclass.