Public class Test1 { privateint t1 = 1; Public int getT1 () { return t1; } Public void setT1 (int t1) { this. T1 = t1; }}
The above is the Test1 class, there is a private T1, the value is 1, gave the Get/set method.
Public class extends Test1 { privateint t1 = 2; Public Static void Main (string[] args) { new Test1 (); New Test2 (); System.out.println (TEST1.GETT1 ()); System.out.println (TEST2.GETT1 ());} }
Above, Test2 inherits the Test1, and also gives a T1 attribute, but the value is 2.
The output is:
1
1
Public classTest2extendsTest1 {Private intT1 = 2; Public intgetT1 () {returnT1; } Public voidSetT1 (intT1) { This. T1 =T1; } Public Static voidMain (string[] args) {Test1 test1=NewTest1 (); Test2 test2=NewTest2 (); System.out.println (TEST1.GETT1 ()); System.out.println (TEST2.GETT1 ()); }}
Test2 inherits the Test1 and also gives a T1 attribute, but the value is 2, which provides a Get/set method.
Output Result:
1
2
Conclusion: The subclass does not inherit the private field of the parent class, only the private field of the parent class is accessed through the GetT1 () method of the public exposed by the parent class, with a value of 1, once the subclass overrides the getT1 () method, the resulting value is changed with a value of 2.
Http://jingyan.baidu.com/article/14bd256e45cc69bb6c261273.html?st=2&net_type=&bd_page_type=1&os=0 &rst=&word=%e6%88%bf%e4%ba%a7%e7%bb%a7%e6%89%bf
Field inheritance problem in Java--subclasses cannot inherit private members of parent class