private字段可继承但无法被使用。因此我们需要用set(),get()方法曲线救国。
注意事项:
子类调用父类的private字段,在子类的构造器中使用super关键字
public static void main(String[] args){
Teacher t = new Teacher("wang",20);
String tName = t.getTeacherName();
int tAge = t.getTeacherAge();
System.out.println(tName + " , " + tAge);
}
}
class Person
{
private String name;
public String getName()
{
return name;
}
void setName(String name)
{
this.name = name;
}
}
class Teacher extends Person
{
private int age;
Teacher(String name,int age)
{
super.setName(name);
this.age = age;
}
public String getTeacherName()
{
String PersonName = super.getName();
return PersonName;
}
public int getTeacherAge()
{
return age;
}
}```
网友评论