class Student extends Person {
private String name = "wzh2";
@Override
public String getName() {
return "子类" + name;
}
public String getParentName(){
//调用父类的方法
return super.getName();
}
public static void main(String[] args) {
Student student = new Student();
System.out.println(student.getName());
System.out.println(student.getParentName());
}
}
public class Person{
//protected意味着子类和同一包中可以访问
protected String name = "wzh";
protected int age = 20;
public String getName() {
return "父类" +name;
}
}
输出结果
子类获取到父类的变量
class Student extends Person{
public void parentDisplay(){
System.out.println(super.age + super.name);
}
public static void main(String[] args) {
new Student().parentDisplay(); //输出结果:20wzh
}
}
public class Person{
//protected意味着子类和同一包中可以访问
protected String name = "wzh";
protected int age = 20;
}
public class Person{
private String name;
private int age;
public void display(){
//通过this或super调用到了Object的toString();
System.out.println(super.toString());
}
public static void main(String[] args) {
new Person().display(); //输出为Person@452b3a41
}
}