天天看點

三元運算符和this

三元運算

文法: 判斷語句   ?   表達式1   :   表達式2

三元運算會得到一個結果,通常用于對某個變量進行指派,當判斷條件成立時,運算結果為表達式1的值,否則結果為表達式2的值。

this

this關鍵字在程式中的三種常見用法:

  1. 通過this關鍵字可以明确地去通路一個類的成員變量,解決與局部變量名稱沖突問題。

public class JBTest_002 {

int age;

public JBTest_002(int age) {

this.age = age;

}

public int getAge() {

return this.age;

}

}

  1. 通過this關鍵字調用成員方法。

public class JBTest_002 {

public void openMouth() {

}

public void speak() {

this.openMouth();

}

}

  1. 構造方法是在執行個體化對象時被Java虛拟機自動調用的,在程式中不能像調用其他一樣去調用構造方法,但可以在一個構造方法中使用“this( [ 參數1 , 參數2….. ] )”

public class JBTest_002 {

public JBTest_002() {

this("zl");

System.out.println("無參的構造方法");

}

public JBTest_002(String name) {

System.out.println("有參的構造方法");

}

}

class ttt {

public static void main(String[] args) {

JBTest_002 test_002 = new JBTest_002();

System.out.println(test_002);

}

}

在使用this調用類的構造方法時,應注意以下幾點。

  1. 隻能在構造方法中使用this調用其他的構造方法,不能在成員方法中使用。
  2. 在構造方法中,使用this調用構造方法的語句必須位于第一行,且隻能出現一次,下面的寫法是非法的。

public JBTest_002() {

String name = "zl";

this(name);

}

  1. 不能在一個類的兩個構造方法中使用this互相調用。

public class JBTest_002 {

public JBTest_002() {

this("zl");

System.out.println("無參的構造方法");

}

public JBTest_002(String name) {

this();

System.out.println("有參的構造方法");

}

}