首页 > 其他 > 详细

构造方法

时间:2020-01-06 19:48:46      阅读:60      评论:0      收藏:0      [点我收藏+]




  1. 构造方法是一个特殊的方法,构造方法名字必须与类名一致,构造方法必须没有返回类型,也就是不编写返回类型


  2. 分类

    • 隐式

      当在一个类中,没有手动编写构造方法,则系统会提供一个默认的无参的构造方法

    • 显示


  3. 构造方法的执行

    当创建对象时自动执行相匹配的构造方法

     Dog d = new Dog();//括号装参数列表
  4. 语法格式:

    public 方法名称([参数列表]){

     ...

    }

class Dog{
    //无参构造方法
    public Dog(){
        //完成对品种、颜色、名字、年龄、性别
        strain = "土狗";
        color = "黑色";
        name = "旺财";
        age = 5;
        sex = '公';
    }
    //编写带参构造方法,完成对属性品种、颜色、名字
    public Dog(String strain,String color,String name){
        //完成局部变量的值,赋给成员变量
        this.strain = strain;
        this.color = color;
        this.name = name;
    }
    //编写对所有属性赋值的构造方法
    public Dog(String strain,String color,String name,int age,char sex){
        this.strain = strain;
        this.color = color;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }




构造方法

原文:https://www.cnblogs.com/huochemeiyouhuo/p/12157751.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!