掌握super与this关键字的运用:
package cn.sg.superthis;
public class Teacher extends People{ private String job; public void eat() { System.out.println("吃饭:套餐B"); } 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; } public void show() { eat(); this.eat(); super.eat(); beat(); this.beat(); }
}
package cn.sg.superthis;
public class People { private String name; private int age; private char gender; public void beat() { System.out.println("打人"); } public void eat() { System.out.println("吃饭:套餐A"); } 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.superthis;
public class Main { public static void main(String[] args) { Teacher teacher = new Teacher(); teacher.setName("小花花"); teacher.setAge(23); teacher.setGender('女'); teacher.setJob("教育事业"); System.out.println(teacher.getName()+" : "+teacher.getAge()+" : "+teacher.getGender()+" : "+teacher.getJob()); teacher.show(); }
}
运行结果:
从main方法开始运行
this.方法:调用本类的方法,若是本类当中没有此方法,则调用父类的方法,父类没有则调用父类的父类方法,以此类推
super.方法:调用父类的方法,父类没有则调用父类的父类方法,以此类推。
直接方法,前面没有super或者this:默认是this.方法