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)