程序的執行優先級與“== and equals”

    計算機畢竟是死的,雖然現在的語言已經爲開發人員提供了足夠的功能幾近於變成傻瓜式編程。但是個人認爲,瞭解代碼在計算機內部的運行過程對程序員是很有幫助的。下面發個測試代碼。
//父類:
public class Person {
  public Person() {
    System.out.println("父類無參數構造器...........6");
  }
  public Person(String name) {
    this();
    System.out.println("父類有參數構造器...........7");
  }
  public static void main(String[] args) {
    System.out.println("父類main方法.............8");
  }//
  //static關鍵字+“{ 遊離塊 }”
  static {
    System.out.println("父類靜態遊離塊...........9");
  }

  {
    System.out.println("父類一般遊離塊...........10");
  }
}
//子類:
public class Student extends Person {
  static String name;//private String name;
  public Student() {
    super("");
    System.out.println("子類無參數構造器..........1");
  }
  public Student(String name) {
    this();
    this.name = name;
    System.out.println("子類有參數構造器...........2");
  }

  public static void main(String[] args) {
    Student s = new Student("zhangsan");
    System.out.println("子類main方法...........3");
  }//

  //static關鍵字+“{ 遊離塊 }”
  static {
    System.out.println("子類靜態遊離塊...........4");
  }//靜態遊離塊只被執行一次;

  {
    System.out.println("子類一般遊離塊...........5");
  }
}
“== and equals”:
“==”比較對象的內存地址;簡單類型內容;
“equals”比較對象的內容
public class TestEquals {
  public int id;

  public TestEquals(int id) {
    this.id = id;
  }
  //重寫equals方法
  public boolean equals(Object obj) {
    if(obj == null) {
      return false;
    }
    if(this == obj) {
      return true;
    }
    if(this.getClass() != obj.getClass()) {
      return false;
    }
    TestEquals s = (TestEquals)obj;
      return this.id == s.id;
  }
}    

class Test {
  public static void main(String[] args) {
    Student s1 = new Student();
    Student s2 = new Student();
//    Student s2 = s1;
    System.out.println(s1.equals(s2));
    //封裝
    Integer a = new Integer(2);
    Integer b = new Integer(4);    
    System.out.println(a.equals(b));
    //簡單
    int x = 3;
    int y = 3;
    System.out.println(x == y);
  }//
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章