方法的重写:父类的访问修饰符不能大于子类的访问修饰符
同级访问修饰符只有private不行,其他三种情况都可以
this 关键字,针对自己
super关键字,针对父类
package cn.sg.upupupupup;
public class Person { private String name; private int age; private char gender; public void eat() { System.out.println("吃饭:套餐A"); } public void eat(String eat) { System.out.println("吃饭:"+eat); } public void sleep() { System.out.println("睡觉"); } 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; }
}
package cn.sg.upupupupup;
public class Teacher extends Person{ private String job; public void eat() { System.out.println("吃饭:套餐B"); } public void eat(String eat,String eat1) { System.out.println("吃饭:两个套餐"+eat+" : "+eat1); } public void shangke () { System.out.println("上课"); } public void beike () { System.out.println("备课"); }
public String getJob() { return job; }
public void setJob(String job) { this.job = job; }
}
package cn.sg.upupupupup;
public class Main { public static void main(String[] args) { Teacher teacher = new Teacher(); teacher.setName("张大师"); teacher.setAge(23); teacher.setGender('男'); teacher.setJob("教育事业"); teacher.eat();//调用子类方法,若子类没有这个方法,再往上调这个方法,知道有这个方法为止 teacher.eat("套餐C");//调用子类方法,若子类没有这个方法,再往上调这个方法,知道有这个方法为止 teacher.eat("套餐C","套餐D");调用子类方法,若子类没有这个方法,再往上调这个方法,知道有这个方法为止
teacher.sleep(); teacher.beike(); teacher.shangke(); System.out.println(teacher.getName()+" : "+teacher.getAge()+" : " + teacher.getGender() +" : " + teacher.getJob() );
}
}
运行结果:
在main方法中调用子类的方法,若子类有该方法则调用
若没有这种方法,则往父类上调,父类没有则往父类的父类上调,以此类推。
属性的调用同理