如何在innerClass之外调用方法?我做了extends方法,但是它告诉我即使我进行了扩展,方法Attributes仍未定义,是因为我无法在类内部扩展类吗?
这是我的代码:
package mainClass;
import java.util.Random;
import mainClass.Characters;
import mainClass.Main;
class Characters {
static String name = "";
static int attack = 0;
static int maxAttack = 0;
static int hp = 0;
static int def = 0;
static class Selena extends Attributes {
private static void main() {
super.Attributes();
//I extend Attributes but why does he not recognize the class Attributes
}
public static void Scratch() {
System.out.println(" uses Scratch!");
}
}
static class Attributes {
Attributes() {
}
}
}
答案 0 :(得分:1)
super.x()
是从父类调用方法的一种方式。
Attributes
不是方法。实际上,粘贴末尾的Attributes() {}
也不是方法。这是一个构造函数。
如果要创建新的Attributes对象,请使用new
关键字,而super
是正确的-不能使用super
来调用此类对象。但是您不必-只需new Attributes();
就可以做到,因为super仅具有一个目的-将您自己的类中对方法的调用与您所用的版本区分开来超越因此:
class Parent {
void hello() {
System.out.println("From parent");
}
}
class Child extends Parent {
void foo() {
hello();
}
}
请注意,在上面的示例中,没有super.
,但是可以正常工作,并且对hello()
的调用将显示"From parent"
。但是:
class Child extends Parent {
void hello() {
// this overrides
System.out.println("From child");
}
void foo() {
hello(); // prints 'from child'
super.hello(); // prints 'from parent'
}
}
此外,super.x()
仅在类本身中有效,而在其任何内部类中均无效,所幸对您的情况无关紧要。
NB:super
用于三个主要到完全不相关的Java功能。泛型逆变边界(这与您所做的工作完全无关,因此我不会进一步研究它),调用方法的父类实现,并选择首先运行哪个父构造函数。最后一个可能是您想要的,但这仅在构造函数本身中有效,并且main
不是构造函数:
class MyAttrs extends Attributes {
public MyAttrs(String x) {
super(x);
}
}
class Attributes {
public Attributes(String x) {
// ....
}
}
看起来像方法的东西都是构造函数。在所有构造函数中,您必须 完全调用父构造函数之一或您自己的父构造函数。如果不这样做,java就会像super();
那样位于方法的顶部。您可以使用super(argsHere)
明确选择要调用的父类的构造函数之一。