Basic concepts of inheritance (1)

Source: Internet
Author: User

One, the limitation of inheritance:

1,) A subclass cannot have more than one parent class, but can inherit multiple layers. In other words, the parent class can also have a parent class.

2) subclasses cannot access private members in the parent class. However, you can call a non-private method in the parent class, but you cannot call a private member directly in the parent class.

For example, the following is a false call to a private member in the parent class

classperson{//defining the Person class    PrivateString name;//define the Name property    Private intAge;//defining The Age property     Public voidsetName (String name) { This. Name =name; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString GetName () {return  This. Name; }     Public intGetage () {return  This. Age; }};classStudentextendsperson{//defining the Student class     Public voidFun () {System.out.println ("The name attribute in the parent class:" +name) ;//error, unable to accessSYSTEM.OUT.PRINTLN ("Age attribute in parent class:" + Age) ;//error, unable to access    }};

However, you can call private member variables indirectly by calling a non-private method in the parent class

classperson{//defining the Person class    PrivateString name;//define the Name property    PrivateintAge;//defining The Age property     Public voidsetName (String name) { This. Name =name; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString GetName () {return  This. Name; }     Public intGetage () {return  This. Age; }};classStudentextendsperson{//defining the Student class     Public voidFun () {System.out.println ("The name attribute in the parent class:" +GetName ()) ;//correct, indirect accessSYSTEM.OUT.PRINTLN ("Age attribute in parent class:" +getage ()) ;//correct, indirect access    }};

Basic concepts of inheritance (1)

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.