构造方法,初始化

/HelloWorld/src/HQ/Bird.java



package HQ;



//
class Bird {

    
    //构造方法
    //没有返回值,不用void
    //方法名跟类名要一样
    //只要自定义了构造方法,就不会自动添加默认构造方法。如果没有自定义,就会自动提供一个默认构造方法(无参数构造)
    //作用:初始化对象
    //只在构造对象时调用
    Bird()
    {
        //完成初始化
         name = "默认鸟名";
    }
    Bird(String birdname)
    {
        //初始化
        name=birdname;
    }
    
    Bird(String birdname,String content)
    {
        //初始化
        name=birdname;
        //this.代表类的本身
        this.content=content;
    }
    

/HelloWorld/src/HQ/ceshiyigelei.java



        //构造方法
        Bird heihei=new Bird("color","weight");
        System.out.println(heihei.Color);
        
View Code
原文地址:https://www.cnblogs.com/1ming/p/5242660.html