Last active
November 10, 2019 16:03
-
-
Save Finomnis/7a6dfbc0da87d7f55ee5450695cd5665 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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