JAVA中对象实例过程以及super关键字

对象实例化 先实例化调用父类构造方法,再调用子类实例化构造方法;

super关键主要是调用父类方法或者属性;

我们修改下上面的实例:

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

42

43

44

45

46

47

48

package com.java.chap03.sec09;

/**

 * 动物类

 * @author user

 *

 */

public class Animal {

    private String name; // 姓名

    private int age;  // 年龄

     

     

    /**

     * 无参父类构造方法

     */

    public Animal() {

        System.out.println("无参父类构造方法");

    }

     

    /**

     * 有参父类构造方法

     * @param name 姓名

     * @param age 年龄

     */

    public Animal(String name,int age) {

        System.out.println("有参父类构造方法");

        this.name=name;

        this.age=age;

    }

     

    public String getName() {

        return name;

    }

    public void setName(String name) {

        this.name = name;

    }

    public int getAge() {

        return age;

    }

    public void setAge(int age) {

        this.age = age;

    }

     

    public void say(){

        System.out.println("我是一个动物,我叫:"+this.name+",我的年龄是:"+this.age);

    }

}

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

42

43

44

45

46

package com.java.chap03.sec09;

/**

 * 定义一个Cat类,继承自Animal

 * @author user

 *

 */

public class Cat extends Animal{

    private String address;

     

    public String getAddress() {

        return address;

    }

    public void setAddress(String address) {

        this.address = address;

    }

    public Cat() {

        super();

        System.out.println("子类无参构造方法");

    }

    public Cat(String name, int age,String address) {

        super(name, age);

        this.address=address;

        System.out.println("子类有参构造方法");

    }

    /**

     * 重写父类的say方法

     */

    public void say(){

        super.say(); // 调用父类的say()方法

        System.out.println("我是一个猫,我叫:"+this.getName()+",我的年龄是:"+this.getAge()+",我来自:"+this.getAddress());

    }

     

    public static void main(String[] args) {

        Cat cat=new Cat("Mini",2,"火星");

        /*cat.setName("Mini");

        cat.setAge(2);*/

        cat.say();

    }

}

运行输出:

有参父类构造方法

子类有参构造方法

我是一个动物,我叫:Mini,我的年龄是:2

我是一个猫,我叫:Mini,我的年龄是:2,我来自:火星

猜你喜欢

转载自blog.csdn.net/weixin_41934292/article/details/88262140
今日推荐