今天我对多态的一般性结论进行总结及实验。
class User{
private String userName;
private String userPassword;
//默认构造方法
public User(){
System.out.println("使用User默认构造方法");
}
//含参数的构造函数 为了检验User u2 = new Student("20140725")不会调用父类含参构造方法
public User(String userName){
this.userName = userName;
System.out.println(userName + " 调用了父类含参数的构造方法");
}
//含两个参数的构造方法,实验User u3 = new Student("","")会不会调用父类构造函数 且Student无此构造方法
public User(String userName,String userPassword){
this.userName = userName;
this.userPassword = userPassword;
System.out.println(userName + " 调用了父类含两个参数的构造方法");
}
//创建子类没有的方法
public String getuserName(){
System.out.println(userName+"成功调用子类没有的方法");
return userName;
}
//创建子类要重写的方法
public void help(){
System.out.println("调用了父类未重写的方法");
}
}
class Student extends User{
private String studentNum;
//默认构造方法
public Student(){
System.out.println("使用Student默认构造方法");
}
//含参数的构造方法且父类没有
public Student(String studentNum){
System.out.println(studentNum+"使用Student含参数的构造方法");
this.studentNum = studentNum;
}
//重写help方法
public void help(){
System.out.println("调用了子类被重写的方法");
}
//构造父类没有 子类特有的方法
public String getstudentNum(){
System.out.println("使用子类特有方法");
return studentNum;
}
}
class ObjectDemo{
public static void main(String[] args){
User u1 = new Student();//实验怎样调用构造方法 运行结果如图1
User u2 = new Student("20140725");//实验含参数的构造方法 运行结果如图2
//User u3 = new Student("20140725","1459"); //实验没有子类构造方法时,如何调用。运行结果如图3。结论1
u1.getuserName(); //实验子类无方法,父类有方法的调用 运行结果如图4。结论2
u1.help(); //实验对象使用重写的方法结果。 运行结果如图5 结论3
//u1.getstudentNum(); //实验能否使用子类特有方法 运行结果如图6。 结论4
}
}
图1
图2
图3
结论1:构造方法先调用父类默认构造方法,而且只会调用默认构造方法,与父类其他构造方法无关。
图4
结论2:在子类没有方法而父类有时,会调用父类的方法。
图5
结论3:子类重写方法会被先调用。符合老师讲的多态对象使用方法规律:先从子类中找,如果没有,去父类中找。
结论4:用多态对象的引用无法操作子类特有的方法,验证它只能操作父类的属性/方法以及子类重写了的方法。