1. static關鍵字
當宣告一個事物是static時,這個域或方法不會與包含它的那個類的任何物件實體關聯在一起,所以,即使未創建某個類的任何物件,也可以呼叫其static方法或者訪問其static域,
一個static欄位對每個類只有一份存盤空間,而非static欄位對每個物件有一個存盤空間,
static方法沒有this的方法,
2. 參考初始化的位置
1)在定義物件的地方,即總能在構造器被呼叫之前被初始化
2)在類的構造器中
3)在正要使用這些物件之前,即惰性初始化,在生成物件不值得及不必要每次都生成物件的情況下,這種方式可以減少額外負擔,
4)使用實體初始化
public class Soap { private String s; Soap(){ System.out.println("Soap()"); s = "Constructed"; } public String toString() { return s; } } public class Bath{ private String // Initializing at point of definition s1 = "Happy", s2 = "Happy", s3, s4; private Soap castille; private int i; private float toy; public Bath() { System.out.println("Inside Bath()"); s3 = "Joy"; toy = 3.14f; castille = new Soap(); } // Instance initialization: { i = 47;} public String tostring() { if(s4 == null) // Delayed initialization: s4 = "Joy"; return "s1 = " + s1 + "\n" + "s2 = " + s2 + "\n" + "s3 = " + s3 + "\n" + "s4 = " + s4 + "\n" + "i = " + i + "\n" + "toy = " + toy + "\n" + "castille = " + castille + "\n"; } public static void main(String[] args) { Bath b = new Bath(); System.out.println(b); } }
3. 為什么需要RTTI(Run-Time Type Identification)
下圖是一個典型的類層次結構圖,基類位于頂部,派生類向下擴展,代碼只操縱對基類的參考,這樣,如果要添加一個新類,來擴展程式,就不會影響原有的代碼,shape類中動態系結了draw()方法,這樣客戶端程式員使用泛化的shape參考來呼叫draw(),即多型,shape物件實際執行什么樣的代碼,是由參考所指向的具體物件Circle、Square或者Triangle而決定的,如果大部分代碼盡可能少的了解物件的具體型別,而只與物件家族中的一個通用表示打交道(在該例中是shape),這樣的代碼更容易些,易讀,易于維護,

abstract class Shape { void draw(){ System.out.println(this + ".draw()"); } abstract public String toString(); }
public class Circle extends Shape{ public String toString(){ return "Circle";} }
public class Square extends Shape{ public String toString(){ return "Square";} }
public class Triangle extends Shape{ public String toString(){ return "Triangle";} }
public class Shapes { public static void main(String[] args) { List<Shape> shapeList = Arrays.asList(new Circle(), new Square(), new Triangle()); for (Shape shape : shapeList) shape.draw(); } }
結果:
Circle.draw()
Square.draw()
Triangle.draw()
4. 抽象類與介面
僅有方法宣告而沒有方法體的方法稱為抽象方法,一個類包含一個或多個抽象方法,該類必須被限定為抽象的,即抽象類,抽象類中允許有普通方法,
介面中的方法都是抽象的,
5. Java泛型為什么使用擦除?
泛型型別只有在靜態型別檢查期間出現,在此之后,程式中的所有泛型型別都將被擦除,替換為它的非泛型上界,例如,list<T>擦除為list,普通的型別變數在未指定邊界的情況下,將被擦除為Object,泛型是Java SE5出現的功能,為了實作遷移兼容性,每個類別庫和應用程式必須與其他所有的部分是否使用了泛型無關,即它們必須不具備探測其他類別庫是否使用了泛型的能力,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/315970.html
標籤:其他
上一篇:HO引擎近況20211015
