1. 程式人生 > >this.方法引數傳遞等

this.方法引數傳遞等

最小作用域最強原則:
區域性變數的作用要比全域性變數作用強


this 
this 指代本類物件
可以呼叫 屬性   方法  和 構造方法
呼叫構造方法  this()  要求必須放在構造方法的第一行
使用this()  呼叫哪個根據攜帶引數型別  個數  順序
this()呼叫構造方法的目的 : 簡化程式碼




class Person{


String name ;


public Person(String name){
this();// 呼叫無引數的構造方法    必須在構造方法的第一行
this.name = name;
this.test();
}


public Person(){
 //this(name,age);

}

public Person(Stirng name,int age){
this(name);
this.age = age;
}


public void test(){


}


//通過呼叫this()呼叫構造方法  能夠簡化程式碼
}


 用一個類作為另外一個類的屬性
作為屬性在類中寫的時候跟其他基本資料型別的屬性格式相同




class Person
{
String name ;
Book book;

public Person(String name,Book book){
this.name = name;
this.book = book;
}
}


// 給類型別屬性賦值


Person p = new Person();


p.name = "fsaf";


// p 物件  想給 book 屬性賦值


Book book ;
//= new Book();


p.book =  book;

p.book.name = "紅樓夢";

p.book.price = 10;





Person p2 = new Person("曹雪芹",book);



// 空指標異常   沒有初始化物件,就去呼叫   , 

//  






  方法的引數傳遞

基本資料型別傳遞的是數值
引用資料型別傳遞的是 地址


特例: String  
常量池的儲存方式;
儲存字串時首先去常量池中查詢相同的字串,如果找到則不去重新開闢空間


如果找不到  則開闢新的空間


public void test(String str){str = str1;


str = "aaa";
}



String str1 = "bbbb";
test(str1);




面向物件的三大特徵   封裝   繼承   多型

封裝:  目的   提高程式碼的 安全性


關鍵字 private  私有的 可以修飾 屬性或者方法    只有本類可以呼叫到


用private將屬性私有化,並且提供對外訪問的介面