标签:
构造代码中定义的是不同对象的共性内容
作用:给对象初始化,对象一建立就运行而且优先于构造函数运行.是给所有对象统一初始化 构造函数是给对应的对象初始化
1 public class Object_StructureCode { 2 public static void main(String[] args) { 3 Person p=new Person(); 4 //p.setName("libushi"); 5 //System.out.println(p.getName()); 6 Person p1=new Person("haungjianfeng"); 7 8 Person p2=new Person("haungjianfeng",21); 9 } 10 } 11 class Person{ 12 private int age; 13 private String name; 14 //构造代码块 15 { 16 speak(); 17 cry(); 18 } 19 20 Person(){ 21 //System.out.println("A:name="+name+",,age="+age); 22 } 23 Person(String name){ 24 this.name =name; 25 //System.out.println("B:name="+name+",,age="+age); 26 27 } 28 Person(String name,int age){ 29 this.name =name; 30 this.age=age; 31 //System.out.println("C:name="+name+",,age="+age); 32 33 } 34 //有了构造函数之后,也要定义set,get方法,用于日后改名字 35 public void setAge(int age){ 36 if (0<age && age<130){ 37 this.age = age; 38 } 39 else 40 System.out.println("feifa age"); 41 } 42 43 public int getAge(){ 44 return age; 45 } 46 47 public void setName(String name){ 48 this.name = name; 49 } 50 public String getName(){ 51 return name; 52 } 53 54 55 public void speak(){ 56 System.out.println("name="+name+",,age="+age); 57 //System.out.println("name="+this.name+",,age="+this.age); 58 } 59 public void cry(){ 60 System.out.println("cry......."); 61 } 62 }
标签:
原文地址:http://www.cnblogs.com/LO-ME/p/3552011.html