super()
是用来调用父构造函数的吗?请解释 super()
。
原文由 Mohan 发布,翻译遵循 CC BY-SA 4.0 许可协议
super()
是用来调用父构造函数的吗?请解释 super()
。
原文由 Mohan 发布,翻译遵循 CC BY-SA 4.0 许可协议
一些事实:
super()
用于调用直接父级。super()
可以与实例成员一起使用,即实例变量和实例方法。super()
可以在一个构造函数中调用父类的构造函数。OK,现在来实际实现一下 super()
的这几点。
查看程序 1 和 2 之间的区别。这里,程序 2 证明了我们在 Java 中的第一个语句 super()
。
方案一
class Base
{
int a = 100;
}
class Sup1 extends Base
{
int a = 200;
void Show()
{
System.out.println(a);
System.out.println(a);
}
public static void main(String[] args)
{
new Sup1().Show();
}
}
输出:
200
200
现在检查程序 2 并尝试找出主要区别。
方案二
class Base
{
int a = 100;
}
class Sup2 extends Base
{
int a = 200;
void Show()
{
System.out.println(super.a);
System.out.println(a);
}
public static void main(String[] args)
{
new Sup2().Show();
}
}
输出:
100
200
在程序 1 中,输出只是派生类的。它无法打印基类和父类的变量。但是在程序 2 中,我们使用了 super()
和变量 a
在打印它的输出时,而不是打印变量 a
的值,它打印了派生类基类的变量 a
的值。所以证明 super()
是用来调用直接父类的。
OK,现在看看程序3和程序4的区别。
方案3
class Base
{
int a = 100;
void Show()
{
System.out.println(a);
}
}
class Sup3 extends Base
{
int a = 200;
void Show()
{
System.out.println(a);
}
public static void Main(String[] args)
{
new Sup3().Show();
}
}
输出:
200
这里的输出是200。当我们调用 Show()
时,调用了派生类的 Show()
函数。但是我们要调用父类的 Show()
函数怎么办呢?查看程序 4 的解决方案。
节目四
class Base
{
int a = 100;
void Show()
{
System.out.println(a);
}
}
class Sup4 extends Base
{
int a = 200;
void Show()
{
super.Show();
System.out.println(a);
}
public static void Main(String[] args)
{
new Sup4().Show();
}
}
输出:
100
200
这里我们得到两个输出,100 和 200。当派生类的 Show()
函数被调用时,它首先调用父类的 Show()
函数,因为在 Show()
派生类的函数,我们通过在函数名前加上 super
关键字来调用父类的 Show()
函数。
原文由 SimonGates 发布,翻译遵循 CC BY-SA 4.0 许可协议
15 回答8.4k 阅读
8 回答6.2k 阅读
1 回答4k 阅读✓ 已解决
3 回答6k 阅读
3 回答2.2k 阅读✓ 已解决
2 回答3.1k 阅读
2 回答3.8k 阅读
super()
调用不带参数的父构造函数。它也可以与参数一起使用。即
super(argument1)
它将调用接受 1 个类型参数的构造函数argument1
(如果存在)。它还可以用于从父级调用方法。即
super.aMethod()
更多信息和教程 在这里