Is the Java compiler allowed for stream sensitivity to static calls?

Here is a short example from the JLS 8.4.8.2 section.

class Super {
    static String greeting() { return "Goodnight"; }
    String name() { return "Richard"; }
}
class Sub extends Super {
    static String greeting() { return "Hello"; }
    String name() { return "Dick"; }
}
class Test {
    public static void main(String[] args) {
        Super s = new Sub();
        System.out.println(s.greeting() + ", " + s.name());
    }
}

According to the discussion of the example, the output of the work main()will be "Goodnight, Dick." This is because static methods are called based on the static type of the called variable / expression.

: , , s , Sub, , , , . ? Java , -, - ?

+5
2

s.greeting() Super.greeting(), s Super, . , . . , , s Sub(), , Sub.name().

Java:

,

myBike.numberOfBicycles

, , .

class-instance wise , - .

+3

Java. "" s.getClass().greeting() :

class A extends Sub {
    static String greeting() { return "Allo"; }
}
class B extends Sub {
    static String greeting() { return "Brrr"; }
}
Super s = condition? new A() : new B();
assert s.greeting.equals(Sub.greeting()); // If compiler cannot infer condition.

? , .

java, s.greeting() .

, ​​.

+1

All Articles