方法的重写,是子类继承父类的方法,但是子类根据自己的要求重新写的新方法比如Object 类中toString()方法,
如果在mian函数中直接system.out.print( 对象 ),那么会出现类似以下的代码:
public class Student {
private int age;
private String name;
public Student() {
}
public Student(int age,String name) {
this.age=age;
this.name=name;
}
public static void main(String[] args) {
Student stu=new Student();
System.out.println(stu);
}
}
结果:
Oop_lianxi.Student@6d06d6
如果重写后:
public class Student {
private int age;
private String name;
public Student() {
}
public Student(int age,String name) {
this.age=age;
this.name=name;
}
public String toString() {
return (name +"-----"+age);
}
//这个方法是继承自:java.lang.Object.toString()
public static void main(String[] args) {
Student stu1=new Student(18,"小丽");
System.out.println(stu);
}
}
结果是:
小丽-----18