赞
踩
声明不变,方法重写
可以同名,但参数列表不能相同(有参无参构造)
子类的全部构造器都会先调用父类的构造器,再执行自己的。
父类构造器 super();
/** * @Author: ggdpzhk * @CreateTime: 2024-08-10 */ public class People { private String name; private int age; public People() { } public People(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "People{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
/** * @Author: ggdpzhk * @CreateTime: 2024-08-10 */ public class Student extends People{ private String school; public Student() { super(); System.out.println("Student()"); } //这个方法很巧妙,当不写学校时,赋值默认学校 public Student(String name, int age) { //子类构造方法第一行都是super,父类的构造方法 super(name, age); this.school = "b站大学"; } public Student(String name, int age, String school) { super(name, age); this.school = school; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } @Override public String toString() { return "Student{" + "school='" + school + '\'' + "name='" + this.getName()+ '\'' + ", age=" + this.getAge() + '}'; } public static void main(String[] args) { Student student = new Student("张三", 18); System.out.println(student.toString()); } }
常见应用场景:为对象中包含父类之部分的成员变量进行赋值
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。