复写的意思就是子类对父类的修改。
复写的条件:
1、在具有父子类关系的两个类当中;
2、父类和子类各有一个函数,这两个函数的定义保持一致(返回值类型、函数名、参数列表)
还是老样子,3个文件来说明。
Person.java:
class Person{
String name;
int age;
Person(){
}
void introduce(){
System.out.println("My name is "+this.name +". My age is " +this.age);
}
}
Student.java:
class Student extends Person{
String address;
void introduce(){
System.out.println("My name is "+super.name +". My age is " +super.age +". My home in " +this.address);
}
}
Test.java:
public class Test{
public static void main(String[] args){
Student li = new Student();
li.name = "liming";
li.age = 18;
li.address = "china";
li.introduce();
Person zhang = new Person();
zhang.name = "zhangsan";
zhang.age = 20;
zhang.introduce();
}
}
输出结果:
PS C:UsersadminDesktopjava_code练习七> java Test
My name is liming. My age is 18. My home in china
My name is zhangsan. My age is 20
PS C:UsersadminDesktopjava_code练习七>
super调用父类函数
修改Person.java:
class Student extends Person{
String address;
void introduce(){
super.introduce();
System.out.println("My name is "+super.name +". My age is " +super.age +". My home in " +this.address);
}
}
修改Test.java:
public class Test{
public static void main(String[] args){
Student li = new Student();
li.name = "liming";
li.age = 18;
li.address = "china";
li.introduce();
}
}
输出结果:
PS C:UsersadminDesktopjava_code练习七> java Test
My name is liming. My age is 18
My name is liming. My age is 18. My home in china