面向对象(构造函数)

class Person

      {

             private String name;

             private int age;

             Person()  

                 {   

                       System.out.println("A:name="+name+",age="+age);

                       cry();

                  }  

            Person(String n)  

                  {   

                         name=n;

                         System.out.println("B:name="+name+",age="+age);  

                         cry();

                   }  

             Person(String n,int a)  

                   {   

                         name=n;

                         age=a;  

                         System.out.println("C:name="+name+",age="+age);  

                         cry();

                    }  

            public void cry()

                 {   

                         System.out.println("cry.......");  

                  }

 }

public class PersonDemo2

        {  

             public static void main(String[] args)

                         {

                                  /*  

                                   * 对象一建立就会调用与之对立的构造函数   

                                   */  

                               Person p=new Person();  

                                 /*   

                                  *  构造函数的作用可以用于给对象进行初始化   

                                  */  

                              Person p1=new Person("lisi");  

                                    /*   

                                      * 构造函数和一般函数的写法上有不同       

                                      * 在运行上也有不同        

                                      * 构造函数是在对象一建立就运行,给对象初始化        

                                      * 而一般方法是对象调用才执行,是对象添加对象具备的功能         

                                      * 一个对象建立,构造函数只能执行一次         

                                      * 而一般方法可以被该对象调用多次   

                                      */  

                               Person p2=new Person("wangwu",20);   

                                 p2.cry();  

                                  p2.cry();  

                 }

}

posted @ 2015-05-08 23:03  冰林  阅读(147)  评论(0编辑  收藏  举报