开发者社区> 问答> 正文

super关键字的用法

super关键字的用法

展开
收起
问问小秘 2020-03-27 16:45:23 853 0
1 条回答
写回答
取消 提交回答
  • super可以理解为是指向自己超(父)类对象的一个指针,而这个超类指的是离自己最近的一个父类。

    super也有三种用法:

    1.普通的直接引用

    与this类似,super相当于是指向当前对象的父类的引用,这样就可以用super.xxx来引用父类的成员。

    2.子类中的成员变量或方法与父类中的成员变量或方法同名时,用super进行区分

    class Person{ protected String name;

    public Person(String name) {
        this.name = name;
    }
    

    }

    class Student extends Person{ private String name;

    public Student(String name, String name1) {
        super(name);
        this.name = name1;
    }
    
    public void getInfo(){
        System.out.println(this.name);      //Child
        System.out.println(super.name);     //Father
    }
    

    }

    public class Test { public static void main(String[] args) { Student s1 = new Student("Father","Child"); s1.getInfo();

    }
    

    }

    3.引用父类构造函数

    super(参数):调用父类中的某一个构造函数(应该为构造函数中的第一条语句)。 this(参数):调用本类中另一种形式的构造函数(应该为构造函数中的第一条语句)。

    2020-03-27 16:46:14
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
建立联系方法之一 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载