In java, the subclass calls the parent class construction method, precautions_Subclass calls the parent class construction method_PJlei’s Blog

There is a characteristic of inheritance, that is, subclasses cannot access parent classprivatefield or privatemethod. For example, the Student class cannot accessPersonnameandagefield: class Person { private String name; private int age; } classStudent extends Person { public String hello() { return “Hello, “ + name; // Compile error: cannot accessname Field } } span> This weakens the role of inheritance. In order to allow subclasses to access the fields of the parent class, we need to change private to protected. Fields modified with protected can be accessed by subclasses: class Person { protected String name; protected int age; } classStudent extends Person { public String hello() { return “Hello, “ + name; // OK! } } Therefore,protected Keywords can control the access rights of fields and methods within the inheritance tree, a protected Fields and methods can be accessed by its subclasses and subclasses of subclasses, which we will explain in detail later. 2. The use of super superThe keyword indicates the parent class (super class). When a subclass refers to a field of the parent class, you can use super.fieldName. For example: class Student extends Person { public String hello() { return “Hello, “ + super.name; } } The…

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索