+ 4

How can i Overload or Override static methods in java ?

24th Jul 2019, 4:08 AM
Govardhan Nayak
Govardhan Nayak - avatar
7 ответов
+ 3
static methods cannot be Overriden in Java. but you can overload them
24th Jul 2019, 4:55 AM
Mind To Machine 💻🕆
Mind To Machine 💻🕆 - avatar
+ 3
class A { static void method() {} } class B extends A{ @Override static void method() {} } zemiak if this is what you mean it gives a compilation error
24th Jul 2019, 3:50 PM
Mind To Machine 💻🕆
Mind To Machine 💻🕆 - avatar
+ 1
practically you can override static with other static method, but they call it 'hiding' then
24th Jul 2019, 11:45 AM
zemiak
+ 1
Mind To Machine 💻🕆 try it without annotation class A { static void method() { System.out.println("A"); } static void method2() { System.out.println("A"); } } class B extends A { static void method() { System.out.println("B"); } public static void main(String args[]){ B.method(); //B B.method2(); //A } }
24th Jul 2019, 4:06 PM
zemiak
+ 1
zemiak static methods are inherited by subclass but cannot be overriding. If you define a static method in subclass with same signature as superclass its just a method belonging to subclass not an overriden one. your code example shows inheritance not overriding. also A a = new B(); a.method(); // method of A class is executed This is because static methods are inherited but not Polymorphic
24th Jul 2019, 4:48 PM
Mind To Machine 💻🕆
Mind To Machine 💻🕆 - avatar
+ 1
give me example of overriding and we can compare it from programer practical view
24th Jul 2019, 7:52 PM
zemiak
24th Jul 2019, 10:36 PM
Mind To Machine 💻🕆
Mind To Machine 💻🕆 - avatar