package 试验;
public class exemple {
public static void main (String[] args)
{
Student stu1=new Student();
stu1.name="仔";
stu1.age=16;
stu1.major="计算机2";
stu1.rest();
Student stu2=new Student("倪仔",6,"计算机");
}
}
class Person{
String name;
int age;
public void rest(){
System.out.println("休息一会?");
}
}
class Student extends Person{
String major;
public void study(){
System.out.println("学习时间");
}
public void rest(){
System.out.println("休息一会");
}
public Student(String name,int age,String major){
this.name=name;
this.age=age;
this.major=major;
}
}
系统说Student stu1=new Student();这一句报错,Student stu2=new Student("倪仔",6,"计算机");还有这一句无法显示内容,不知道这是为什么?求解
Student stu1=new Student();
因为你没有定义无参数构造函数
加上
public Student(){
this.name=“default name”;
this.age=0;
this.major="default major";
}
Student stu2=new Student("倪仔",6,"计算机");
这个本身不会输出什么,下面写
stu2.study();
stu2.rest();
当类没有写构造函数的时候默认有一个无参构造,但是你如果加上有参构造函数,那么无参构造函数就不会默认加上了,必须手动加上