class Sundae{
private Sundae(){System.out.println("Sundae");}
static Sundae sundaeMake(){
System.out.println("SundaeMake");
return new Sundae();
}
}
public class IceCream{
public static void main(String[] args)
{
Sundae x = Sundae.sundaeMake();
}
}在Sundae x =Sundae.sundaeMake()处,为什么不能用new 关键字?
private Sundae(){System.out.println("Sundae");}
static Sundae sundaeMake(){
System.out.println("SundaeMake");
return new Sundae();
}
}
public class IceCream{
public static void main(String[] args)
{
Sundae x = Sundae.sundaeMake();
}
}在Sundae x =Sundae.sundaeMake()处,为什么不能用new 关键字?
private Sundae()
没有办法new了。为什么构造器设计成private,那就要谈“编程”以外的东西了——设计。
“私有的!!只有我自己可以用,其他类不能用!!”,呵呵,所以你要是在IceCream这个类中通过这个“自私”的构造器创建对象,就给拒绝了,呵呵。但是为什么通过static Sundae sundaeMake()这个方法又可以呢?
你没有给这个方法赋予访问权限(权限就是private,protected之类的)你只是说明这个方法是static的(静态方法),所以就默认是包访问权限了,(我猜你这两个类是同一个包的,就是默认包,我想你把他们放到同一个文件夹)同一个包的类当然可以方法包访问权限的方法拉,呵呵,所以你通过这个包访问权限的方法创建对象就成功了。