当前位置: 代码迷 >> Java相关 >> 类中可以实例化自己吗?
  详细解决方案

类中可以实例化自己吗?

热度:270   发布时间:2006-12-03 20:33:56.0
类中可以实例化自己吗?
最近看书越看越糊涂,类中能实例化自己吗?希望有人能给讲一下,最好举个例子看看
main()方法好像不属于任何一个类,它是程序的入口对不?
搜索更多相关的解决方案: 实例  

----------------解决方案--------------------------------------------------------

当然可以实例化自己,main是程序的入口!


----------------解决方案--------------------------------------------------------
下面是自已瞎编的一个程序,编绎无法通过,如果类中可以实例化自己,这个有何不可?

public class Mytest{
static{
Mytest A=new Mytest();
}

public static void print(){
System.out.println("abc");
}
public static void main(String[] args) throws IOException{
A.print();
}
}
----------------解决方案--------------------------------------------------------
static应该在main 前面执行吧,先让它把自己给实例化掉,可结果出错了
----------------解决方案--------------------------------------------------------

你之所以为错,是因为
static{
Mytest A=new Mytest();
}
执行了,但是Mytest A只在static块里面有用


----------------解决方案--------------------------------------------------------

rt

[此贴子已经被作者于2006-12-4 23:04:06编辑过]


----------------解决方案--------------------------------------------------------

是作用域的问题!我也长记性了!


----------------解决方案--------------------------------------------------------
好像是吧,有没有比较好一点儿证明例子?
----------------解决方案--------------------------------------------------------
随便举个例子

import java.sql.Date;
/**
*
* @author v
*/
public class User {

private String name;
private String address;
private Date birthday;

public String getName() {
return name;
}

public String getAddress() {
return address;
}

public Date getBirthday() {
if( birthday!=null )
return (Date)birthday.clone();
return null;
}

private User( String aName, String aAddress, Date aBirthday ){
name = aName;
address = aAddress;
birthday = aBirthday;
}

public static User createMe(){
return new User( "xiachi","nanning",Date.valueOf("1985-06-12") );
}



//Test this User class
public static void main(String args[]){
User me = User.createMe();
System.out.println( me.getName() );
System.out.println( me.getAddress() );
System.out.println( me.getBirthday() );
}
}

----------------解决方案--------------------------------------------------------
public static User createMe(){
return new User( "xiachi","nanning",Date.valueOf("1985-06-12") );
}

这样就自己实例化了自己

----------------解决方案--------------------------------------------------------
  相关解决方案