超级关键字用法

我是 java 的新手,我有几个基本问题:

  1. 静态变量/方法使用什么内存?

  2. 关键字“Super”是否仅在 Method overriding 的情况下才有意义?


婷婷同学_
浏览 133回答 4
4回答

UYOU

关键字super可用于:声明泛型类型:public class Foo<E super Bar> { // <=====&nbsp; &nbsp; ...}从子类构造函数调用基类构造函数:public class Bar {&nbsp; &nbsp; private int id;&nbsp; &nbsp; public Bar(int id) {&nbsp; &nbsp; &nbsp; &nbsp; this.id = id;&nbsp; &nbsp; }}public class Foo extends Bar {&nbsp; &nbsp; public Foo(int id) {&nbsp; &nbsp; &nbsp; &nbsp; super(id); // <=====&nbsp; &nbsp; }}当子类隐藏字段时,访问基类中的字段:public class Foo extends Bar {&nbsp; &nbsp; private int id;&nbsp; &nbsp; public int getFooId() {&nbsp; &nbsp; &nbsp; &nbsp; return this.id;&nbsp; &nbsp; }&nbsp; &nbsp; public int getBarId() {&nbsp; &nbsp; &nbsp; &nbsp; return super.id; // <=====&nbsp; &nbsp; }}从重写的子类方法调用基类方法:public class Bar {&nbsp; &nbsp; public void doGreatWork() {&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; }}public class Foo extends Bar {&nbsp; &nbsp; @Override&nbsp; &nbsp; public void doGreatWork() {&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; &nbsp; super.doGreatWork(); // <=====&nbsp; &nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; }}当子类重写方法时引用基类方法public class MultiBar extends Bar {&nbsp; &nbsp; public void doGreatWork() {&nbsp; &nbsp; &nbsp; &nbsp; list.stream().forEach(super::doGreatWork); // <=====&nbsp; &nbsp; }}

慕村225694

静态变量/方法使用什么内存?如果我们想访问或调用该方法,我们不需要创建对象,只需在编写方法时使用 static 关键字,如 ->> public static show()。当我们使用 static 关键字时,该类将被调用并执行该方法。static 意味着我们不能改变值,我们也可以对变量使用 static 关键字,一旦我们使用 static 关键字就意味着我们不能经常改变值。例子:public class static example&nbsp;{&nbsp; public static void main(String[] args)&nbsp;{&nbsp; &nbsp;xyz.i = 10;&nbsp; &nbsp;xyz.show();&nbsp; }&nbsp; }&nbsp; class xyz&nbsp;{&nbsp; static int i;&nbsp; public static void show()&nbsp; {&nbsp; &nbsp;System.out.println("Stackoverflow example by Me");&nbsp; }&nbsp; }

慕尼黑5688855

关键字“Super”是否仅在 Method overriding 的情况下才有意义?当我们要调用父类的方法时,子类的方法将在方法重载中执行,因为父类和子类将具有相同的方法名。这就是方法重载发生的原因。为了克服这个问题,我们使用 super 关键字来调用父类方法,即使父类和子类同名。我们可以轻松调用并执行父类方法例子:&nbsp; &nbsp;class A {&nbsp; &nbsp; int i;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; public void show(){&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("A");&nbsp; &nbsp; }}class B extends A {&nbsp; &nbsp; int i;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; public void show(){&nbsp; &nbsp; &nbsp; &nbsp; super.show()&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("B");&nbsp; &nbsp; }}public class overriding example {&nbsp; &nbsp; public static void main(String[]args) {&nbsp; &nbsp; &nbsp; &nbsp; B obj1 = new B();&nbsp; &nbsp; &nbsp; &nbsp; obj1.show();&nbsp; &nbsp; }}

慕斯709654

当父类和子类都有同名成员时访问父类的数据成员,显式调用父类的无参数参数化构造函数,当子类重写该方法时访问父类的方法。它可用于访问父类的变量,调用父类的构造函数,并可用于方法覆盖的情况。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java