21xrx.com
2024-09-17 04:23:46 Tuesday
登录
文章检索 我的文章 写文章
学习Java中的super关键字
2023-06-12 15:44:23 深夜i     --     --
Java super 继承

我在学习Java的时候,经常使用到super关键字。super关键字是用来调用父类中的属性或方法的。下面我来分享一下super关键字的使用方法和示例代码。

1. 调用父类的属性

在子类中,我们可以使用super关键字来调用父类中的属性。示例代码如下:


public class Parent

  protected String name = "parent";

public class Child extends Parent {

  private String name = "child";

  

  public void print() {

    System.out.println("Parent name: " + super.name);

    System.out.println("Child name: " + this.name);

  }

}

public class Main {

  public static void main(String[] args) {

    Child child = new Child();

    child.print();

  }

}

输出结果为:


Parent name: parent

Child name: child

可以看到,使用super.name调用了Parent类中的name属性,而this.name调用的是Child类中的name属性。

2. 调用父类的方法

除了调用属性外,我们还可以使用super关键字来调用父类中的方法。示例代码如下:


public class Parent {

  public void print() {

    System.out.println("I am parent.");

  }

}

public class Child extends Parent {

  public void print() {

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

    System.out.println("I am child.");

  }

}

public class Main {

  public static void main(String[] args) {

    Child child = new Child();

    child.print();

  }

}

输出结果为:


I am parent.

I am child.

可以看到,使用super.print()调用了Parent类中的print方法。

3. 调用父类的构造方法

在子类中,我们也可以使用super关键字来调用父类的构造方法。示例代码如下:


public class Parent {

  public Parent(String info) {

    System.out.println("Parent constructor with " + info);

  }

}

public class Child extends Parent {

  public Child() {

    super("info"); // 调用父类的构造方法

    System.out.println("Child constructor.");

  }

}

public class Main {

  public static void main(String[] args) {

    Child child = new Child();

  }

}

输出结果为:


Parent constructor with info

Child constructor.

可以看到,使用super("info")调用了Parent类中的构造方法。

以上就是我对Java中的super关键字的一些学习和使用方法的分享。希望能对广大Java爱好者有所帮助。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复