类中的构造方法实例化的时候自动执行

在实例化一个类时,类中的构造方法自动执行的,例如:

 1 class Demo{
 2     private static int count=0;
 3     public Demo(){
 4         count++;
 5         System.out.println("产生了"+count+"个对象");
 6     }
 7 }
 8 
 9 public class StaticDemo06{
10     public static void main(String args[]){
11         new Demo();
12         Demo d1=new Demo();
13         new Demo();
14     }
15 }

结果是:

产生了1个对象
产生了2个对象
产生了3个对象

猜你喜欢

转载自www.cnblogs.com/whitemaple/p/9212229.html