好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java继承的实现与继承限制分析

本文实例讲述了java继承的实现与限制。分享给大家供大家参考,具体如下:

java继承的实现

继承的实现

1.继承的基本概念

扩展父类的功能

2.java中使用 extends 关键字完成继承。

示例代码:

?

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

29

30

31

32

33

34

35

36

37

38

39

40

41

public class extendsdemo01 {

   static class person{

     private int age;

     private string name;

     public int getage() {

       return age;

     }

     public void setage( int age) {

       this .age = age;

     }

     public string getname() {

       return name;

     }

     public void setname(string name) {

       this .name = name;

     }

     public void tell(){

       system.out.println( "姓名: " +getname()+ " 年龄:" +getage());

     }

   }

   static class student extends person{

     private int score;

     public int getscore() {

       return score;

     }

     public void setscore( int score) {

       this .score = score;

     }

     public void say(){

       system.out.println( "成绩:" +getscore());

     }

   }

   public static void main(string [] args){

     student s= new student();

     s.setage( 20 );

     s.setname( "张三" );

     s.setscore( 100 );

     s.tell();

     s.say();

   }

}

运行结果:

姓名: 张三  年龄:20
成绩:100

java中继承的限制

1、在java中只允许单继承。

2、子类不能直接访问父类的私有成员。

示例代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

public class extendsdemo02 {

   static class people{

     private int age;

     public int getage() {

       return age;

     }

     public void setage( int age) {

       this .age = age;

     }

   }

   static class worker extends people{

     public void tell(){

       system.out.println(getage());

     }

   }

   static class petworker extends worker{

   }

   public static void main(string [] args){

     worker worker= new worker();

     worker.setage( 100 );

     worker.tell();

   }

}

运行结果:

100

希望本文所述对大家java程序设计有所帮助。

原文链接:https://blog.csdn.net/YANG_Gang2017/article/details/78177457

查看更多关于Java继承的实现与继承限制分析的详细内容...

  阅读:13次