1.掌握方法的重写
Java 方法重载和重写的区别 重载: 1.方法参数个数、类型、顺序不同
重写: 1.方法名,参数,参数类型,返回值要一致
2.子类去重写父类的方法,在main方法调用的时候优先使用子类的方法,也就是就近原则
示例代码:
package cn.sg.upupupupu;
public class Person { private String name; private int age; private char gender; public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public char getGender() { return gender; }
public void setGender(char gender) { this.gender = gender; }
public void eat() { System.out.println("吃饭:西红柿鸡蛋"); } public void sleep() { System.out.println("睡觉"); }
}
package cn.sg.upupupupu;
public class Teacher extends Person{ private String job; public String getJob() { return job; } public void setJob(String job) { this.job = job; } public void shangke() { System.out.println("上课"); } public void beike() { System.out.println("备课"); } //方法的重写:重写父类的方法 public void eat() { System.out.println("吃饭:隆江猪脚饭"); }
}
package cn.sg.upupupupu;
public class Main { public static void main(String[] args) { Teacher teacher = new Teacher(); teacher.setName("老师"); teacher.setAge(18); teacher.setGender('男'); System.out.println(teacher.getName()+" : "+teacher.getAge()+" : "+teacher.getGender()+" : "); teacher.eat();//就近原则: }
}
运行结果:
Author:枫叶