今天学了什么
练习习题:用Person类完成Student类和Teacher类。
接口Outline:
package personstudentteacher;
public interface Outline {
public void task();
}
父类Person类:
package personstudentteacher;
public abstract class Person {
public String name;// 外部类都可访问
protected int age; //子类包可访问,其他类不可访问
public Person(){ //抽象类的构造函数,在生成子类对象时,被子类默认调用
System.out.println("Person的无参构造函数!");
}
public Person(String name,int age){
this.name=name;
this.age=age;
}
public void IDcard(){
System.out.println("Name: "+name+"; " +"Age: "+age);
}
public static void eat(){
System.out.println("进食!");
}
public abstract void work();
}
Student类:
package personstudentteacher;
public class Student extends Person{
public String snum; //默认值为 null
//子类的构造函数,必须调用父类的构造函数,形式为: super(); 编译器可提供
Student(){
super();//生成子类对象时,默认调用父类构造函数
System.out.println("Student的无参构造函数");
}
Student(String name,int age,String snum){ //构造函数重载
super(name,age); // 调用父类方法
this.snum=snum;
}
public void IDcard(){ //重写父类此方法
//super.IDcard();
System.out.println("Name: "+name+"; "+"Age: "+age+"; "+"Snum: "+snum);
}
public void work(){
System.out.println("好好学习!");
}
}
Teacher类:
package personstudentteacher;
public class Teacher extends Person implements Outline {
private double wage;
public double getwage(){
return wage;
}
public void setwage(double wage){
this.wage=wage;
}
public Teacher(String name,int age){ //构造函数重载
super(name,age); // 调用父类方法
}
public void work(){
System.out.println("好好育人!");
}
public void task(){ //继承并实现接口
System.out.println("勤勤恳恳的工作!");
}
}
Test测试类:
package personstudentteacher;
public class Test {
public static void main(String[] args){
Student SNo1=new Student("JLei",25,"001");
SNo1.IDcard();
Student SNo2=new Student();
Person PNo2=SNo2; //向上转型:将子类对象赋值给父类引用
//一个引用能够调用哪些变量和函数,取决于这个引用的类型
PNo2.name="XiaoHong";
PNo2.age=20;
//一个引用调用某个具体方法(继承中可能出现子类复写父类方法),取决于它指向的对象
PNo2.IDcard();// 这里调用了子类的方法
//向下转型:将父类对象赋值给子类引用 是面向对象多态性的体现
Person PNo3=new Student(); //先必须向上转型
Student SNo3=(Student)PNo3;
SNo3.IDcard();
System.out.println("
");
Teacher TNo1=new Teacher("王老师",40);
TNo1.IDcard();
TNo1.work();
TNo1.eat();
TNo1.task();
}
}
运行结果截图:
遇到的问题
Test测试类中,Student类的实例化,有参构造格式需要注意,String型要加引号,int型不能加。
明天计划
学习第12章 用I/O进行数据处理