首页 > 技术文章 > 构造方法-带参

penphy 2019-05-27 08:55 原文

 1 /*
 2         //编写狗类,属性:品种、颜色、名字、年龄、性别,方法:输出狗的信息
 3 */
 4 class Dog{
 5     //无参构造方法
 6     /*public Dog(){
 7         //完成对品种、颜色、名字、年龄、性别
 8         breed = "中华田园犬";
 9         color = "黑色";
10         name = "旺财";
11         age = 3;
12         sex = '公';
13     }
14     */
15     //编写带参构造方法,完成对属性品种、颜色、名字赋值
16     public Dog(String breed,String color,String name){  //()里的写的就是带参参数
17         //完成局部变量的值,赋给成员变量
18         this.breed = breed;
19         this.color = color;
20         this.name = name;
21     }
22     //编写对所有属性赋值的构造方法
23     public Dog(String breed,String color,String name,int age,char sex){    //()里的写的就是带参参数
24         this.breed = breed;
25         this.color = color;
26         this.name = name;
27         this.age = age;
28         this.sex = sex;
29     }
30     //属性也叫做成员变量
31     String breed;
32     String color;
33     String name;
34     int age;
35     char sex;
36     //方法:输出狗的信息
37     public void print(){
38         System.out.println("品种:" + breed + "\n颜色:" + color + "\n名字:" + name + "\n年龄: "+ age + " \n性别:" + sex);
39     }
40 }
41 //编写狗的测试类
42 class DogTest{
43     public static void main(String[ ]args){
44         //实例化狗
45         /*Dog Tom = new Dog();
46         //第一种方法:完成对对象中的属性,使用引用名称.属性名称 = 值;
47         Tom.breed = "泰迪";
48         Tom.color = "黄棕色";
49         Tom.name = "Tom";
50         Tom.age = 2;
51         Tom.sex = '母';
52         Tom.print();
53         */
54         //第二种方法:完成对对象中的属性赋值,使用构造方法完成 
55         //当创建对象时自动执行相匹配的构造方法
56         //无参构造方法输出
57         /*Dog d1 = new Dog();
58         d1.print();
59 
60         System.out.println("--------------------");
61         Dog d2 = new Dog();
62         d2.print();
63         */
64         
65         System.out.println();
66         //带参构造方法输出
67         Dog d3 = new Dog("泰迪","黄色","拉拉");
68         d3.print();
69 
70         System.out.println();
71         //创建对象同时完成对所有属性赋值
72         Dog d4 = new Dog("拉布拉多","白色","taylor",3,'母');
73         d4.print();
74     }
75 }

 

输出结果:

推荐阅读