问题
I am working on a class with an inner class
My code:
package com.solignis;
public class Config {
public static final Target target;
class Target {
public void create(String targetName) {
System.out.println("Created" + targetName);
}
public void destroy(String targetName) {
System.out.println("Destroyed" + targetName);
}
}
}
IntelliJ doesn't see anything wrong with the subclass but it keeps complaining that I have not initalized the static variable target
. But when I try to initialize it with something like null
I get a null pointer exception (no surprise there!) but I don't what I could initialize the variable with since as far I can understand all its just an instance of the Target subclass in the Example superclass (is this right?). Also Target
has no constructor so I cannot declare new
on target
in order to initialize the variable.
So what could I do?
Please correct me if I am incorrect about my understanding of this I am still trying to wrap my head around the more "deeper" workings of Java.
回答1:
The variable test
is indeed not initialized:
public static Test test;
Initialization means putting value into the variable, i.e. something like this: test = SOMETHING;
The SOMETHING may be either null
or an instance of the type of the variable. In your case:
test = null;
test = new Test();
are valid expressions.
Indeed if you put null to the test
you cannot "use" it, i.e. invoke its method or access its member variables.
BTW. Test
is not a subclass of Example
as probably you think. It is its inner class. Subclass is a class that extends other class. Actually Test
is a direct subclass of object.
回答2:
in fact you can initialize a class that you do not declared a constructor for it it has a default constructor with no argument
test = new Test();
来源:https://stackoverflow.com/questions/16747456/why-is-intellij-telling-me-this-variable-has-not-been-initialized