面向对象10:Super详解

super注意点:
  1. super调用父类的构造方法,必须在构造方法的第一个
  2. super 必须只能出现在子类的方法或者构造方法中;
  3. super 和 this 不能同时调用构造方法
super VS this:
  • 代表对象不同:

    this:本身调用者的这个对象
    super:代表父类对象的应用

  • 前提:

    this:没有继承也可以使用
    super:只能在继承条件才可以使用

  • 构造方法

    this();本类的构造
    super():父类的构造

name的对应:

代码示例:

application.java

package com.oop.Demo05;


public class Application2 {
    public static void main(String[] args) {
  Student2 s1 = new Student2();
s1.test("秦疆");
    }
}

输出:

秦疆
qingjiang
kuangshen

进程已结束,退出代码 0

student2.java

package com.oop.Demo05;

public class Student2 extends Person2{
    private String name = "qingjiang";


    public void test(String name) {  //不加static,调用方法得用student2类里的
        System.out.println(name);   //传递的参数
        System.out.println(this.name);  //当前类里的
        System.out.println(super.name); //父类里的

    }
}

person2.java

package com.oop.Demo05;

public class Person2 {
    protected String name = "kuangshen";

}

调用方法:

supper的注意点:
super注意点:
1、super调用父类的构造方法,必须在构造方法的第一个
2、super必须只能出现在子类的方法或者构造方法中
3、super和this不能同时调用构造方法

super和this的区别:
    代表的对象不同:
        this:本身调用者这个对象
        super:代表父类对象的应用
    前提:
        this:没有继承也可以使用
        super:只能在继承条件下才可以使用
    构造方法:
        this():本类的构造
        super():父类的构造

application2.java

package com.oop.Demo05;


public class Application2 {
    public static void main(String[] args) {
        Student2 s1 = new Student2();
        // s1.test("秦疆");

        s1.test();

    }
}

输出:

person2无参执行了
haha
student2无参执行了
student2
student2
person2

进程已结束,退出代码 0

Student2.java

package com.oop.Demo05;

public class Student2 extends Person2{
    public Student2() {
//        super(); //super和this只能存在一个,super调用的父级
        this("haha"); //this调用的有参
        System.out.println("student2无参执行了");
    }

    public Student2(String name) {
        this.name = name;
        System.out.println(name);
    }

    private String name = "qingjiang";

    public void print() {
        System.out.println("student2");
    }

    public void test() {  //不加static,调用方法得用student2类里的
//        System.out.println(name);   //传递的参数
//        System.out.println(this.name);  //当前类里的
//        System.out.println(super.name); //父类里的

        print();
        this.print();
        super.print();
    }
}

Person2.java

package com.oop.Demo05;

public class Person2 {
    public Person2() {
        System.out.println("person2无参执行了");
    }

    protected String name = "kuangshen";

    public void print() {
        System.out.println("person2");
    }
}
posted @ 2020-08-14 19:57  nkndlawn  阅读(170)  评论(0)    收藏  举报