Java 我们可以在方法之外但在类内部创建对象吗?如果是,那么什么';在类之外创建对象的目的是什么?
这部分Java 我们可以在方法之外但在类内部创建对象吗?如果是,那么什么';在类之外创建对象的目的是什么?,java,class,object,Java,Class,Object,这部分 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
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?
}
这是C类的属性
C c1 = new C();
是对某个方法的调用,不允许在作用域中调用它,可以在其他类方法中调用该方法,也可以在该类中调用该方法,但要在方法内部调用。这只是范围
c1.p();
表示创建名为c1
的C
类型的类变量,并对其进行初始化。您可以将其初始化为null
C c1 = new C();
或者根本没有
C c1 = null;
但是,您不能在方法范围之外使用它,比如调用p()
方法代码>是字段声明。在字段声明期间,为其赋值是有效的。
c1.p()代码>语句不会在方法或块(静态或实例块)内调用。
在没有其他要求的方法或块中执行此操作是有效的。
但是,如果您在其他位置执行此操作,则必须使用它来指定您要声明的字段。
例如,这是合法的:
C c1;
我们可以在方法之外但在类内部创建对象吗
是的。当然
如果是,那么在类方法(我想你指的是方法)之外创建对象的目的是什么
如果您希望类的实例保持另一个对象的状态,那么您还希望如何实现这一点
考虑以下类别:
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();
}
}
c1是C的成员。应该允许班级有成员,对吗?欢迎加入。你的问题我不清楚。“我们可以在方法外部但在类内部创建对象吗?”-可以。你可以。“在类之外创建对象的目的是什么?”它与发布的代码有什么关系?它与问题的第一部分有什么关系?我不清楚问题是什么,但java允许在类内创建对象,因为有两个原因,第一个是可以从多个方法使用的公共对象,第二个是聚合和组合关系。您可以调用静态方法,由way@cricket_007您不能调用任何类型的方法,除非它在另一个方法或静态块中调用,或用于分配变量这是不合法的。当你说“但是你不能在方法范围之外使用它,就像调用p()方法一样。”为什么我们不能调用p方法呢?原因是什么?它没有超出范围,因为它在类中。@Nitish类提供定义,而不是功能。c1
实例的任何使用都必须在另一个方法范围内。
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() );
}