继承与方法重写
提纲:1.继承的语法格式
2.方法重写
3.自动转型
1.继承的语法格式:
1.1继承的关键字:extends
格式:
public class 类名(子类,超类,派生类) extends 类名(父类,基类) {
}
1.2子类继承父类属性和方法的情况
a.子类和父类在同一个包下,能调用的方法和属性:
只有私有的属性和方法不能在子类中和子类的对象调用。
b.子类和父类不同包,能调用的属性和方法:
子类中: 公有的,受保护的属性和方法
子类的对象:公有的属性和方法
packge stu; public class Student { //定义两个属性 public String name; private int score; /** * 构造方法 */ public Student(){ this("王五",5) /** * 构造方法 给属性赋值初始值 */ public Student(String name,int score){ //赋值 this.name = name; this.score = score; } public void setName(String name){ this.name = name; } public String getName(){ return name; } public void setScore(int score){ this.score = score; } public int getScore(){ return score; } /** * 定义学习方法 */ public void study(){ score++; System.out.println(name+"学习中,学分是"+score); } } /** * 定义一个UNStudent类,该类继承自Student */ public class UNStudent extends Student { public void test(){ System.out.println("UNStudent Test"); } }