class Student { private String name; private int age; //函数的重载 :函数名相同、参数的个数不同或类型不同、返回值不做要求、同一个类当中 public Student() { System.out.println("不带有参数的构造方法"); } public Student(String name) { this.name = name; System.out.println("带有一个参数的构造方法"); } public Student(String name,int age) { this.name = name; this.age = age; System.out.println("带有两个参数的构造方法"); } @Override public String toString() { return "Student{" + "name='" + name + ''' + ", age=" + age + '}'; } } public class GouZaoFangFa { public static void main(String[] args) { Student student = new Student("mayu"); System.out.println((student.toString())); Student student1 = new Student(); Student student2 = new Student("xiaoqu",23); } }
运行结果
**问题:**以前的类当中也没有写过构造方法,为啥没有报错?
当没有写构造方法时,编译器会帮助你默认生成一个不带参数的构造方法
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)