【发布时间】:2021-06-11 09:13:56
【问题描述】:
如果构造函数是在创建对象时隐式调用的函数,那么我们应该在构造函数中声明变量,但它会报错。
class A{
public A(){
int a =5;
}
}
public class assignment2 {
public static void main(String[] args) {
A obj = new A();
System.out.println(obj.a);
}
}
错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
a cannot be resolved or is not a field
at ass2.main(ass2.java:14)
【问题讨论】:
-
当然可以。它只存在于该构造函数中,而不存在于它之外。
标签: java oop constructor