Given the code below:
class Super {
static
String greeting() { return "Goodnight"; }
String greetingx() { return "Goodnight"; }
String name() { return "Richard"; }
}
class Sub extends Super {
static String greeting() { return "Hello"; }
String greetingx() { return "Hello"; }
String name() { return "Dick"; }
}
class TestStat {
public static void main(String[] args) {
Super s = new Sub();
System.out.println(s.greeting() + ", " + s.name());//Goodnight, Dick
System.out.println(((Sub)s).greeting() + "," +s.name());//Hello,Dick (1)
System.out.println(((Super)s).greeting() + ", " + s.name());//Goodnight,Dick (2)
System.out.println(((Sub)s).greetingx() + ", " + s.name());//Hello, Dick
System.out.println(((Super)s).greetingx() + ", " + s.name());//Hello, Dick
Super s1 = new Super();
//System.out.println(((Sub)s1).greeting() + ", " + s1.name());//ClassCasTException
}
}
in comments in front of the SOP's I showed the output.
I know that static methods calls are based on the reference type, and that instance methods are called based on the type of the object pointed to by the refernce type.
I also know that a cast does not change the class of an object; it only checks that the class is compatible with the specified type.
Can someone please explain me in detail how the output for the static method calls results in (1) and (2)
I thought we should get for both Goodnight Dick
Does the cast operator have an influence if the methods are static instead of instance ???
Thanx