“`”
<h2>super 关键字</h2>
super关键字用于从子类访问父类的变量和方法。 例如:</p>
<pre><code>public class Super { protected int number; protected showNumber() { System.out.println(""number = "" + number); }}public class Sub extends Super { void bar() { super.number = 10; super.showNumber(); }}</code></pre>
在上面的例子中,Sub 类访问父类成员变量 number 并调用其其父类 Super 的 <code>showNumber()</code> 方法。
<strong>使用 this 和 super 要注意的问题:</strong>
<ul><li>在构造器中使用 <code>super()</code> 调用父类中的其他构造方法时,该语句必须处于构造器的首行,否则编译器会报错。另外,this 调用本类中的其他构造方法时,也要放在首行。</li><li>this、super不能用在static方法中。</li></ul>
<strong>简单解释一下:</strong>
被 static 修饰的成员属于类,不属于单个这个类的某个对象,被类中所有对象共享。而 this 代表对本类对象的引用,指向本类对象;而 super 代表对父类对象的引用,指向父类对象;所以, <strong>this和super是属于对象范畴的东西,而静态方法是属于类范畴的东西</strong>。
<pre><code> "“`
Was this helpful?
0 /
0