50 面向对象构造方法Constructor概述和格式

构造方法的概述和作用

  给对象的数据(属性)进行初始化

 

构造方法格式特点

  方法名与类名相同 大小写也要一致

  没有返回值,连void都没有

  没有具体的返回值 return

 

 

构造方法的注意事项

  如果我们没有给出构造方法,系统自动提供一个无参数的构造方法

  如果我们给出了构造方法,系统将不会提供无参数的构造方法

 

 1 class Demoe2_Construtor{
 2     public static void main(String[] args) {
 3         Person p1 = new Person();
 4         Person p2 = new Person("blit",20);
 5 
 6         p2.show();
 7 
 8         Person p3 =  new Person("li",80);
 9         p3.show();
10 
11         
12     }
13 }
14 
15 
16 class Person{
17     private String name;
18     private int age;
19 
20     public Person(String name,int age){
21         this.name = name;
22         this.age =age;
23         System.out.println("有参数的构造方法");
24     }
25 
26     public void show(){
27         System.out.println(age+":"+name);
28     }
29 }

 

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