How does the "this" keyword in Java inheritance work? -


in below code snippet, result confusing.

public class testinheritance {     public static void main(string[] args) {         new son();         /*         father father = new son();         system.out.println(father); //[1]i know result "i'm son" here         */     } }  class father {     public string x = "father";      @override     public string tostring() {        return "i'm father";     }      public father() {         system.out.println(this);//[2]it called in father constructor         system.out.println(this.x);     } }  class son extends father {     public string x = "son";      @override     public string tostring() {         return "i'm son";     } } 

the result is

i'm son father 

why "this" pointing son in father constructor, "this.x" pointing "x" field in father. how "this" keyword working?

i know polymorphic concept, won't there different between [1] , [2]? what's going on in memory when new son() triggered?

all member functions polymorphic in java default. means when call this.tostring() java uses dynamic binding resolve call, calling child version. when access member x, access member of current scope (the father) because members not polymorphic.


Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -