我可以看到无法在方法中创建非静态类的静态对象吗?
代码:
public class Rent {
public void abc() {
System.out.println("Non static method");
}
public static void def() {
System.out.println("this is static method");
}
}
public class SampleJava {
public static void main(String[] args) {
Rent r1 = new Rent();
public static Rent r2; //not allowed in static method
}
public static Rent r3; //allowed outside method
public void def() {
Rent r4 = new Rent();
public static Rent r5; //not allowed in non-static method either
}
}
答案 0 :(得分:6)
您必须考虑几点:
静态数据类似于静态方法。它与实例无关。声明为static的值没有关联的实例。它存在于每个实例中,并且仅在内存中的单个位置声明。如果它发生变化,它将针对该类的每个实例进行更改。
您使用的访问修饰符仅允许用于类级别而不是方法级别。 在您的示例中:
public static void main(String[] args) {
Rent r1 = new Rent();
public static Rent r2; //Will give compile time error.
}
考虑到“静态”的目的,如果要在方法中声明静态对象,则其范围将仅绑定到该特定方法。
通常静态对象用于维持状态。
例如您的数据库连接逻辑可能具有单例类,并且此类的对象应保持数据库连接状态。 这些对象必须是并且必须处于类级别。
答案 1 :(得分:2)
您获得的错误与静态/实例访问无关。由于Java语法无效,它们只是编译时错误。
您不能使用public
和static
等字段修饰符来声明方法内的局部变量(无论是静态方法还是实例方法)。
只需删除不必要的修饰符:
public static void main(String[] args) {
Rent r1 = new Rent();
Rent r2;
}
public static Rent r3;
public void def() {
Rent r4 = new Rent();
Rent r5;
}
答案 2 :(得分:1)
首先,不允许在方法中使用访问修饰符(public,private,protected)声明变量。您也不应该在方法中将变量声明为static
。
您在方法之外声明的那些变量是类的成员。
有两种类型的变量:
我可以看到无法在方法中创建非静态类的静态对象吗?
静态意味着它属于该类。它甚至在您实例化对象之前就存在了。这就是你可以直接在类中调用静态方法的原因。
那么什么是静态成员?
示例:
class Pond
{
static double waterTemp = 17.5; //Every Pond object shares the same value
int numFishes; //Belongs to each individual Pond object
}
如何访问静态成员:
System.out.println(Pond.waterTemp); //Preferred
System.out.println(Pond.numFished); //Not allowed
//OR
Pond pond = new Pond();
System.out.println(pond.waterTemp); //Not necessary, but allowed
System.out.println(pond.numFished); //The only way to get numFishes
答案 3 :(得分:0)
非静态方法与实例关联,因此需要在访问实例之前创建实例。但是,静态方法与类有关,因此即使没有实例也应该可以使用。这些约束导致静态方法不能在非静态方法中创建。