CoreJava/exp3/ExtendsDemo.java

89 lines
1.6 KiB
Java
Raw Permalink Normal View History

2024-05-09 09:10:51 +08:00
package exp3;
//类-人
class Person{
//成员变量
String name; //姓名
int age; //年龄
//无参构造"人"
public Person(){
this.name = "无名";
this.age = 18;
}
//有参构造"人"
public Person(String name, int age){
this.name = name;
this.age = age;
}
//设置姓名
void setName(String name){
this.name = name;
}
//设置年龄
void setAge(int age){
this.age = age;
}
//行为-吃饭
void eat(Person p){
System.out.println(p.name+"吃饭");
}
//行为-睡觉
void sleep(Person p){
System.out.println(p.name+"睡觉");
}
}
//类-学生 继承自类-人
class Student extends Person{
//成员变量
String id;
//无参构造
public Student(){
super();
this.id = "0000";
}
//有参构造
public Student(String name, int age, String id){
super(name, age);
this.id = id;
}
//设置id
void setId(String id){
this.id = id;
}
//行为-学习
void study(Student s){
System.out.println(s.name+"学习");
}
//方法-展示信息
void show(){
System.out.println("姓名: "+this.name);
System.out.println("年龄: "+this.age);
System.out.println("学号: "+this.id+"\n");
}
}
public class ExtendsDemo {
public static void main(String[] args){
Student s1 = new Student();
Student s2 = new Student("梦之空", 20, "2230502119");
s1.show();;
s2.show();
}
}