Super详解

super表示父类的,因此super关键字常用在父子类中。

super关键字的用法:

  • super .属性表示调用父类中的属性。
  • super .方法(参数列表)表示调用父类的方法。
  • super( )表示调用父类的无参构造方法,当创建子类对象的时候,默认会调用父类的无参构造方法。
  •  super(参数列表)表示调用父类的有参构造。


在子类的构造过程中不管是无参构造还是有参构造,都默认会调用父类的无参构造方法,如果父类没有构造方法,可以使用super([参数列表])引用,如果构造子类的无参构造,就使用super()语句调用父类的无参构造方法。如果构造子类的有参构造,就使用super(参数列表)语句调用父类的有参构造方法。

super注意点:

1. super调用父类的构造方法,必须在构造方法的第一个。

2. super必须只能出现在子类的方法或者构造方法中。

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

super对比this:

1. 代表的对象不同。

2. this:本身调用者这个对象。

3. super:代表父类对象的引用。

前提:this在没有继承的情况下也能使用,super只能在继承条件下才可以使用。

构造方法区别:

1. this();默认调用本类的构造

2. super():父类的构造

案例一

创建一个Person类

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

创建一个Student类

public class Student extends Person{
    private String name = "linfeng";
    public void test(String name){
        System.out.println(name);//昊天
        System.out.println(this.name);//linfeng
        System.out.println(super.name);//林枫
    }
}

创建一个Application类

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

运行结果:

 

案例二

创建一个Person类

public class Person{
    //私有的东西无法被继承
    public void print(){
        System.out.println("Person");
    }
}

创建一个Student类

public class Student extends Person {
    public void print() {
        System.out.println("Student");
    }
    public void test1(){
        print(); //Student
        this.print(); //Student
        super.print();  //Person
    }
}

创建一个Application类

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

运行结果:

 

案例三:

创建一个Person类

public class Person{
    public Person(){
        System.out.println("Person无参执行了");
    }
    public void print(){
        System.out.println("Person");
    }
}

创建Student类

public class Student extends Person {
public Student(){
    //隐藏代码supper();:调用了父类的无参构造器
    //调用父类的构造器,必须要在子类的第一行
    System.out.println("Student无参执行了");
}
    public void print() {
        System.out.println("Student");
    }
    public void test1(){
        print();
        this.print();
        super.print();
    }
}

创建一个Application类

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

运行结果:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

疯狂的小鸡仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值