复写:
如果子类中重复定义了父类中已有的属性,
则称此子类中的属性复写了父类中的属性
格式:
class Super
{
访问权限 方法返回值类型 方法 1(参数 1)
{}
}
class Super extends Super
{
访问权限 方法返回值类型 方法 1(参数 1) 复写父类中的方法
{}
}
例子:
class Person
{
String name;
int age;
public String talk()
{
return "我是: "+name+" 今年 :"+age+" 岁";
}
}
class Student extends Person
{
String school;
public Student(String name, int age,String school)
{
this.name=name;
this.age=age;
this.school=school;
}
public String talk() //复写Person中的talk()方法
{
return "我在 "+school+" 上学";
}
}
public class Text
{
public static void main(String[] agrs)
{
Student c=Student("陈三",19,"四川");
System.out.println(c.talk());// 此时调用的是子类中的 talk()方法
}
}
输出结果是:我在四川上学
注意:如果在子类中 talk()方法处并没有声明权限,不声明则权限为 default,但父类中的 talk 方法有 public,而 public 权限要高于 default 权限,如果不声明子类的方法比父类中拥有更严格的访问权限,那么会出现错误。