Skip to content

Instantly share code, notes, and snippets.

@Finomnis
Last active November 10, 2019 16:03
Show Gist options
  • Save Finomnis/7a6dfbc0da87d7f55ee5450695cd5665 to your computer and use it in GitHub Desktop.
Save Finomnis/7a6dfbc0da87d7f55ee5450695cd5665 to your computer and use it in GitHub Desktop.
public class Test {
private static class A{
public static void test(){
System.out.println("A:test");
}
void dynamic(){
System.out.println("A:dynamic");
}
}
private static class B extends A{
public static void test(){
System.out.println("B:test");
}
@Override
void dynamic(){
System.out.println("B:dynamic");
}
}
public static void main(String[] args) {
A.test(); // A:test
B.test(); // B:test
//A.dynamic() - doesnt work, requires object to run
//B.dynamic() - doesnt work, requires object to run
A aa = new A();
aa.test(); // A:test
aa.dynamic(); // A:dynamic
B bb = new B();
bb.test(); // B:test
bb.dynamic(); // B:dynamic
A ab = new B(); // works because B is a subclass of A
ab.test(); // A:test
ab.dynamic(); // B:dynamic
/*
Reason: ab.test is static, so which one gets called depends on the reference, not the actual object. Static functions dont know anything about objects.
ab.dynamic is not static, so which one gets called depends on the object type.
*/
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment