Why can't a static method hide an instance method in 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");
    } 
}

The test class is a superclass, and Fest is a subclass, because we know that static methods cannot be overridden, even then I get an error, for example, "the static method cannot hide the instance method in java", can someone explain this, thanks in advance.

+4
source share
4 answers

The term redefinition usually refers to objects, because using the same parent link, you can call different methods from this child object. Therefore, static methods cannot be overridden because they are associated with a reference type, not an object type.

? , . , , , . :

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");
    } 
}

, . . , .

1:

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"
    }
}

2: ( )

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");
    }
}

2: ( )

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");
    }
}
+2

, .

, , , , , , , .

0

In this case, something seems to Fest t = new Fest(); t.tests()be too confusing: what does it mean? Calling an inherited instance method Test.test? Or a call to a static method Fest?

0
source
ClassA{

   public void disp(){}

//Error ,We can not define two members with same name (Note this till next step)
  //public static void disp(){}

}

ClassB extends ClassA{

//Now ClassB has one method disp() inherited from ClassA.
//Now declaring a static method with same 
//Error, as mentioned ClassB already has disp() and one more member with same //name is not allowed.
  //public static void disp(){}
}
0
source

Source: https://habr.com/ru/post/1612563/


All Articles