51 面向对象给成员变量赋值的两种方式的区别

一个是  setXxx() 方法

一个是 构造方法

 

构造方法给属性进行初始化

setXxx()方法是来修改属性值

 

如果是在开发中使用,使用setXxx()方法来修改属性的值

 

 1 class Demo3_Construtor{
 2     public static void main(String[] args) {
 3         Person p1 = new Person("ooo",80);
 4         p1 = new Person("ooo",81);// new了一个新的对象;
 5         System.out.println(p1.getName()+p1.getAge());
 6 
 7 
 8         Person p2 = new Person();
 9         p2.setName("pan");
10         p2.setAge(89);
11 
12         System.out.println(p2.getAge()+p2.getName());
13         
14     }
15 }
16 
17 
18 class Person{
19     private String name;
20     private int age;
21 
22     public Person(){
23 
24     }
25 
26     public Person(String name,int age){
27         this.name  = name;
28     }
29 
30     public void setName(String name){
31         this.name = name;
32 
33     }
34 
35     public void setAge(int age){
36         this.age = age;
37     }
38 
39     public String getName(){
40         return this.name;
41     }
42 
43     public int getAge(){
44         return this.age;
45     }
46 }

 

posted @ 2017-01-25 22:11  panw3i  阅读(183)  评论(0编辑  收藏  举报