1. "Overwrite" private method
public class Privateoverride { private void F () {print ("Private f ()");} public static void Main (string[] args) { privateoverride po = new Derived (); PO.F (); }} Class Derived extends Privateoverride {public void F () {print (' public f () ')}}/* Output:private f () *///:~
Because the private method is automatically considered the final method, and the exported class is masked. Therefore, in this case, the F () method in the derived class is a completely new method, and since the F () method in the base class is not visible in the subclass derived, it cannot even be overloaded.
The conclusion is that only non-private methods can be overwritten.
2. Domain and Static methods
Only normal method calls can be polymorphic.
Class Super {public int field = 0; public int GetField () {return field;}} Class Sub extends Super {public int field = 1; public int GetField () {return field;} public int Getsuperfield () {return super.field;}} public class Fieldaccess {public static void Main (string[] args) { Super sup = new Sub ();//Upcast System.ou T.println ("Sup.field =" + Sup.field + ", sup.getfield () =" + Sup.getfield ()); Sub Sub = new sub (); System.out.println ("Sub.field =" + Sub.field + ", sub.getfield () =" + Sub.getfield () + ", Sub.getsuperfi Eld () = "+ Sub.getsuperfield ());} } /* Output:sup.field = 0, Sup.getfield () = 1sub.field = 1, Sub.getfield () = 1, Sub.getsuperfield () = 0*///:~
When a sub object is transformed into a super reference, any domain access operations are parsed by the compiler and therefore not polymorphic . In this example, different storage spaces are allocated for Super.field and Sub.field. This way, the sub actually contains two fields called field and it gets from the super. However, the default domain generated when referencing a field in a sub is not a super version of the Field field. Therefore, in order to obtain Super.field, the Super.field must be explicitly indicated.
If a method is static, its behavior is not polymorphic.
Class Staticsuper {public static String Staticget () { return "Base staticget ()"; } Public String Dynamicget () { return ' Base dynamicget () '; }} Class Staticsub extends Staticsuper {public static String Staticget () { return "Derived staticget ()"; } Public String Dynamicget () { return ' Derived dynamicget () ';} } public class Staticpolymorphism {public static void Main (string[] args) { staticsuper sup = new staticsub (); Upcast System.out.println (Sup.staticget ()); System.out.println (Sup.dynamicget ());} } /* Output:base staticget () Derived dynamicget () *///:~
A static method is associated with a class, not a single object. There is no dynamic allocation mechanism for calls to static methods. When a program invokes a static method, the method to be called is selected at compile time, that is, which method is called based on the type of the reference being declared.
Considerations in Java Polymorphism