Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why static method cannot hide instance method in java

Tags:

java

class TestOverriding {

    public static void main(String aga[]) {
        Test t = new Fest();
        t.tests();
    }
}

class Test {
    void tests() {
        System.out.println("Test class : tests");
    }
}
class Fest extends Test {   
    static void tests() {
        System.out.println("Fest class : tests");
    } 
}

Test class is super class and Fest is it's sub class as we know static methods can not be overridden even then i am getting error like "static method cannot hide instance method in java" can someone explain this, thanks in advance.

like image 987
Gajendra Kumar Avatar asked Sep 27 '22 10:09

Gajendra Kumar


1 Answers

The term overriding is generally referred for objects because using same parent reference, you can call different methods from given child object. In this manner, static methods cannot be overridden because they are associated with reference type, not object type.

How overriding happens? You specify a method in base class and put same signature in child class, this automatically overrides the method. If you note, static methods are also inherited, i.e., if a parent class contains a static method, then it can be used by child class reference. For example:

public class TestOverriding {

    public static void main(String aga[]) {
        Fest t = new Fest();
        t.tests(); <-- prints "Test class : tests"
    }
}

class Test {
    static void tests() {
        System.out.println("Test class : tests");
    }
}
class Fest extends Test {   
    void tests3() {
        System.out.println("Fest class : tests");
    } 
}

Now, a static method has come to your child class and you are trying to define a new method in child class with same signature. This is causing the problem. If you are doing it in a single class, error message would be different.

Case 1: same class

class Fest{   
    void tests3() {
        System.out.println("Fest class : tests3");
    } 
    static void tests3() {
        System.out.println("Fest class : static tests3"); <-- gives "method tests3() is already defined in class Fest"
    }
}

Case 2: child class (static to instance)

class Test {
    static void tests() {
        System.out.println("Test class : tests");
    }
}
class Fest extends Test {   
    void tests() { <-- gives "overridden method is static"
        System.out.println("Fest class : tests");
    }
}

Case 2: child class (instance to static)

class Test {
    oid tests() {
        System.out.println("Test class : tests");
    }
}
class Fest extends Test {   
    static void tests() { <-- gives "overriding method is static"
        System.out.println("Fest class : tests");
    }
}
like image 178
Amber Beriwal Avatar answered Nov 15 '22 05:11

Amber Beriwal