您好,欢迎来到化拓教育网。
搜索
您的当前位置:首页【基础】super详解

【基础】super详解

来源:化拓教育网

1,调用属性

public class Application {

    public static void main(String[] args) {
        Student student = new Student();
        student.test("application");
    }
}

//类分割线///

public class Student extends Person {
    private String name="Student";

    public void test(String name){
        System.out.println(name);
        System.out.println(this.name);
        System.out.println(super.name);
    }
}

//类分割线

public class Person {
    protected String name="Person";
}

2,方法调用

public class Application {

    public static void main(String[] args) {
        Student student = new Student();
        student.test1();
    }
}

///类分割线/

public class Student extends Person {
    private String name="Student";

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

    public void test1(){
        print();
        this.print();
        super.print();
    }
}

///类分割线/


public class Person {
    protected String name="Person";

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

注意:如果Person类里面的方法或者属性,变为private修饰的话,则子类不可调用(私有的东西不可以被继承)

3,构造器

public class Application {

    public static void main(String[] args) {
        Student student = new Student();
    }
}

///类分割线/


public class Student extends Person {
    private String name="Student";

    public Student() {
        //隐藏代码,默认调用了父类的无参构造
        //super();//此行数据必须放到这个构造器的第一行,否则会报错,如果要调用this()(本类构造)也必须在第一行
        System.out.println("student构造器执行");
    }
}


///类分割线/


public class Person {
    protected String name="Person";

    public Person() {
        System.out.println("person构造器执行");
    }
}

super注意点:

1,super调用父类的构造方法,必须再子类构造方法的第一行

2,super只能出现再子类的构造方法或者方法中

3,super和this不能同时调用构造方法

this VS super:

代表的对象不同:       

        this:本身调用者这个对象

        super:代表父类对象的应用

前提:

        this:没有继承也可以使用

        super:只能再继承条件才可以使用

构造方法:

        this():本类的构造

        super():父类的构造

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo9.cn 版权所有 赣ICP备2023008801号-1

违法及侵权请联系:TEL:199 18 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务