public class C
{
public void p() { System.out.println(" method p"); }
public static void main(String[] args) {System.out.println(" main method");}
C c1 = new C(); // Why java allows this? that is, creating object outside of
//the methods but inside the class?
//For what purpose does Java allowed this? when is this needed?
c1.p(); //This generates error, Why is this not allowed?
}
答案 0 :(得分:1)
C c1 = new C();
是一个字段声明
在现场声明期间,为其分配值是有效的。
不在方法或块(静态或实例块)内调用c1.p();
语句。
在没有其他要求的方法或块中进行此操作是有效的。
但如果你在其他地方这样做,必须用它来指定你宣布的字段。
例如,这是合法的:
public class C
{
public void p() { System.out.println(" method p"); }
public C newC(){
return new C();
}
public static void main(String[] args) {System.out.println(" main method");}
C c1 = new C(); // Why java allows this? that is, creating object outside of
//the methods but inside the class?
//For what purpose does Java allowed this? when is this needed?
C c2 = c1.newC();
public void myMethod(){
c1.p();
}
}
答案 1 :(得分:0)
这部分
C c1 = new C();
这是C类的属性
c1.p();
是对某个方法的调用,不允许在范围内调用它,可以在其他类方法或此类中但在方法内部调用该方法。这只是范围
答案 2 :(得分:0)
C c1 = new C();
表示您创建名为C
的{{1}}类型的类变量并对其进行初始化。您可以将其初始化为c1
null
或者根本不是
C c1 = null;
但是,您无法在方法范围内使用它,例如调用C c1;
方法。
答案 3 :(得分:0)
我们可以在方法之外但在类中创建一个对象吗?
是。当然
如果是,那么在
类方法之外创建对象的目的是什么(我认为你的意思是方法)?
如果你希望你的类的实例保持另一个对象的状态,那么你期望怎么做呢。
考虑以下课程:
class C
{
// member of C instances
private List<String> list = new ArrayList<>();
// constructor
public C ()
{}
// How else would you add to the member list if
// it wasn't declared outside of methods?
public void addString (String s)
{
list.add (s);
}
// return the size of the list
public int count ()
{
// Should I create a new list in here... No, that wouldn't make
// sense. I should return the size of the member list that
// strings may have been added to with the addString method.
return list.size();
}
}
让我们看看这个:
public static void main (String[] args)
{
// Create a new C instance
C c = new C();
// I sure hope C is keeping track of all these strings??
c.addString( "1" );
c.addString( "2" );
// Should print 2
System.out.println( "Number of strings: " + c.count() );
}