Java基础之extends用法详解及简单实例

2025-05-29 0 22

Java extends用法详解

概要:

理解继承是理解面向对象程序设计的关键。在Java中,通过关键字extends继承一个已有的类,被继承的类称为父类(超类,基类),新的类称为子类(派生类)。在Java中不允许多继承。

(1)继承

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25
class Animal{

void eat(){

System.out.println("Animal eat");

}

void sleep(){

System.out.println("Animal sleep");

}

void breathe(){

System.out.println("Animal breathe");

}

}

class Fish extends Animal{

}

public class TestNew {

public static void main(String[] args) {

// TODO Auto-generated method stub

Animal an = new Animal();

Fish fn = new Fish();

an.breathe();

fn.breathe();

}

}

在eclipse执行得:

?

1

2
Animal breathe!

Animal breathe!

java文件中的每个类都会在文件夹bin下生成一个对应的.class文件。执行结果说明派生类继承了父类的所有方法。

(2)覆盖

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28
class Animal{

void eat(){

System.out.println("Animal eat");

}

void sleep(){

System.out.println("Animal sleep");

}

void breathe(){

System.out.println("Animal breathe");

}

}

class Fish extends Animal{

void breathe(){

System.out.println("Fish breathe");

}

}

public class TestNew {

public static void main(String[] args) {

// TODO Auto-generated method stub

Animal an = new Animal();

Fish fn = new Fish();

an.breathe();

fn.breathe();

}

}

执行结果:

?

1

2
Animal breathe

Fish breathe

在子类中定义一个与父类同名,返回类型,参数类型均相同的一个方法,称为方法的覆盖。方法的覆盖发生在子类与父类之间。另外,可用super提供对父类的访问。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

原文链接:http://blog.csdn.net/qq_35101189/article/details/57425283

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 Java基础之extends用法详解及简单实例 https://www.kuaiidc.com/118445.html

相关文章

发表评论
暂无评论