//"人"类文件
public class Person {
public int age = 18;
public double high = 180.5;
public char sex = '男';
}
//"学生"类文件
public class Student extends Person{
public String colleague = "清华大学";//学校...
public String subject = "Java编程语言";//主修学科...
public int stage = 1;//大一、大二...
@Override
public String toString() {
return "Student{" +
"colleague='" + colleague + '\'' +
", subject='" + subject + '\'' +
", stage=" + stage +
", sex=" + sex +
'}';
}
}
//测试类文件
public class Try {
public static void main(String[] args) {
Student stu = new Student();
System.out.println(stu);
}
}
public class Try {
public static void main(String[] args) {
Student stu = new Student();
System.out.println(stu.colleague);
System.out.println(stu.high);
System.out.println(stu.money);
}
}
public void sleep(){
super.sleep();
System.out.println("大学生在睡觉");
}
5. 子父类构造方法问题
若在父类中定义了构造方法,子类继承了父类,在子类完成构造前,先要帮父类进行构造,不然报错
Java复制代码
//"人"类中定义构造方法
public class Person {
public int age;
public double high;
public char sex;
Person(int age,double high,char sex){
this.age = age;
this.high = high;
this.sex = sex;
}
}
//"学生"类中定义构造方法
public class Student extends Person{
public String colleague;//学校...
public String subject;//主修学科...
public int stage;//大一、大二...
public char sex;
Student(String colleague,String subject,int stage,char sex){
this.colleague = colleague;
this.subject = subject;
this.stage = stage;
this.sex = sex;
}
}
//测试方法中实例化对象
Student stu = new Student("北京大学","Java数据结构",2,'男');
//Person类
public class Person {
public int age;
public double high;
public char sex;
static{
System.out.println("Person类的静态代码块被调用");
}
{
System.out.println("Person类的构造代码块被调用");
}
public Person(int age,double high,char sex){
this.age = age;
this.high = high;
this.sex = sex;
System.out.println("Person类构造方法被调用");
}
}
//Student类
public class Student extends Person{
public String colleague;//学校...
public String subject;//主修学科...
public int stage;//大一、大二...
public char sex;
static{
System.out.println("Student类的静态代码块被调用");
}
{
System.out.println("Student类的构造代码块被调用");
}
public Student(String colleague,String subject,int stage,char sex){
super(18,180.5,'男');
this.colleague = colleague;
this.subject = subject;
this.stage = stage;
this.sex = sex;
System.out.println("Student类构造方法被调用");
}
}
//测试类,注意我实例化类两个对象
public class Try {
public static void main(String[] args) {
Student stu = new Student("北京大学","Java数据结构",2,'男');
System.out.println("============================");
Student stus = new Student("浙江大学","Java微服务",3,'男');
}
}