java复写文件_java基础(八)之函数的复写/重写(override)

复写的意思就是子类对父类的修改。

复写的条件:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值