Reputation: 95
How do I call a method outside the innerClass? I did the extends method but it told me that the method Attributes is undefined even though I did extends, is it because I can't extend a class inside a class?
Here's my code:
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() {
}
}
}
Upvotes: 0
Views: 496
Reputation: 102872
super.x()
is a way to invoke methods from your parent class.
Attributes
is not a method. In fact, that Attributes() {}
at the very end of your paste isn't a method either; it's a constructor.
If you want to make a new Attributes object, you use the new
keyword, and super
is right out - you can't use super
to invoke such things. But you don't have to - just new Attributes();
will do it, because super has only one purpose - that is to differentiate the call to the method in your own class vs. the version you overrode. Thus:
class Parent {
void hello() {
System.out.println("From parent");
}
}
class Child extends Parent {
void foo() {
hello();
}
}
Note how in the above example there is no super.
and yet that will work fine, and the call to hello()
would print "From parent"
. But:
class Child extends Parent {
void hello() {
// this overrides
System.out.println("From child");
}
void foo() {
hello(); // prints 'from child'
super.hello(); // prints 'from parent'
}
}
Furthermore, super.x()
is only valid in the class itself and not any inner class thereof, which fortunately doesn't matter for your case.
NB: super
is used for three mostly to completely unrelated java features. Generics contravariant bounds (this is completely unrelated to what you're doing, so I won't delve into it further), invoking the parent class implementation of methods, and picking which constructor of parent to run first. That last one may be what you want, but that is only valid in constructors themselves, and main
is not a constructor:
class MyAttrs extends Attributes {
public MyAttrs(String x) {
super(x);
}
}
class Attributes {
public Attributes(String x) {
// ....
}
}
Both of the looks-like-a-method thingies are constructors; You MUST invoke exactly one of your parent constructors, OR one of your own, as first thing in any constructor. If you fail to do so, java acts as if super();
is at the top of your method. You can use super(argsHere)
to explicitly choose one of the constructors of your parent class to invoke.
Upvotes: 1