Created
February 9, 2018 11:45
-
-
Save jigewxy/7fbcf2f1f73e977cb08047c552fba1b1 to your computer and use it in GitHub Desktop.
methodhiding on static method
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
package study.tonight; | |
class Animal { | |
public static void showlog(){ | |
System.out.println("static: parent method invoked"); | |
} | |
public void foo(){ | |
System.out.println("parent foo() method invoked"); | |
} | |
} | |
class Monkey extends Animal { | |
//static method always stick with the reference type, not run time object. | |
//so overriding won't happen | |
public static void showlog(){ | |
System.out.println("static: child method invoked"); | |
} | |
public void showChildLog(){ | |
System.out.println("unique child method invoked"); | |
} | |
public void foo(){ | |
System.out.println("child foo() method invoked"); | |
} | |
} | |
public class MethodHiding { | |
public static void main(String[] args) { | |
Animal a = new Monkey(); | |
Monkey b = new Monkey(); | |
// a.showlog(); //use parent method, overriding is not happening because the method is static | |
// b.showlog(); | |
// a.showChildLog(); as available methods binds with reference type, so a doesn't have the child method. | |
// b.showChildLog(); | |
//Monkey.showlog(); | |
a.foo(); // use child method, overriding happens | |
b.foo(); // use child method | |
// write your code here | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment