Field inheritance problem in Java--subclasses cannot inherit private members of parent class

Source: Internet
Author: User

 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.