重写方法必须与被重写方法具有相同的方法名称,参数列表和返回类型
[b]疑问如下[/b]:
如果名称不同的话也可以运行出自己想要的结果,这样重写的作用又在哪里?
[b]疑问如下[/b]:
如果名称不同的话也可以运行出自己想要的结果,这样重写的作用又在哪里?
class Person{
private String name;
private int age;
public void setName(String name){this.name = name;}
public void setAge(int age){this.age = age;}
public String getName(){return name;}
public int getAge(){ return age; }
public String getInfo(){
return "Name = " +name+"\n"+"age = "+age;
}
}
//继承父类Person
class Student extends Person {
private String school;
public String getSchool(){return school;
}
public void setSchool(String school){this.school = school;}
//方法的重写/override/overwrite
//原来为public String getInfo()
public String GetInfo(){
return "Name = "+getName()+"\nage = "+getAge()+"\nschool = "+school;
}
}
public class Testoverride{
public static void main(String args[]){
Student student = new Student();
Person person = new Person();
person.setName("none");
person.setAge(100);
student.setName("Yusheng");
student.setAge(22);
student.setSchool("SMU");
System.out.println(person.getInfo());
//原来为System.out.println(student.getInfo());
System.out.println(student.GetInfo());
}
}