为什么我们不能将实例变量传递给超类构造函数?
可能的重复:
显式调用实例方法时无法引用实例方法构造函数
我已经尝试这样做很长时间了。
public class bb extends test {
int t = 23;
public bb() {
super(t); //**This is the place that error comes**
// TODO Auto-generated constructor stub
}
public bb(int v) {
}
}
public class test {
public test() {
// TODO Auto-generated constructor stub
}
public test(int v) {
// TODO Auto-generated constructor stub
}
}
控制器类
class s {
public static void main(String[] args) {
bb sd = new bb();
System.out.println("sdfsdfsdfd");
}
}
这是出现的错误。我想知道为什么实例变量不能传递给超类构造函数?我怀疑这是因为构造函数没有可访问的实例。
线程“main”java.lang.Error 中出现异常:未解决的编译问题: 显式调用构造函数时无法引用实例字段 t
Possible Duplicate:
Cannot refer to a instance method while explicitly invoking a constructor
I have been trying to do this for long time.
public class bb extends test {
int t = 23;
public bb() {
super(t); //**This is the place that error comes**
// TODO Auto-generated constructor stub
}
public bb(int v) {
}
}
public class test {
public test() {
// TODO Auto-generated constructor stub
}
public test(int v) {
// TODO Auto-generated constructor stub
}
}
Controller class
class s {
public static void main(String[] args) {
bb sd = new bb();
System.out.println("sdfsdfsdfd");
}
}
This is the error that comes. I want to know why a instance variable can't be passed to a super class constructor? I suspect that it's because there is no instance accessible to the constructor.
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot refer to an instance field t while explicitly invoking a constructor
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您将该变量设置为静态变量,则错误将会消失。发生这种情况是因为
一旦调用其构造函数,就会创建实例变量,但在本例中是在调用该
变量 之前创建的。 >子类的构造函数其父构造函数被执行..这意味着
子类的实例变量/对象不存在于堆中。或者换句话说,它们还没有被构造。但是对于
静态变量
,它们是第一个被执行的变量,因此它们有一些值并且工作得很好。
If you make that variable as a
static
variable that error will disappear.. this happens becauseInstance Variables
are created once its constructor is called but here in this case before thechild's constructor
its parent Constructor gets executed.. which means instance variables/object ofchild class doesn't exist in the Heap. or in other words they are not constructed yet.. but in case
of
static variables
they are first one's getting executed thus they have some values and that worksperfectly fine..