複用代碼是Java衆多引人注目的功能之一,但要成爲極具革命性的語言,僅僅可以複製代碼並對之加以改變是不夠的,它還必須可以作更多的事情。ide
就是在當前類中產生現有類的對象。函數
每個非基本類型的對象都有該方法,當編譯器須要一個String但你只有一個對象時,該方法會自動調用。代理
編譯器並非簡單的爲每個引用都建立對象,由於這回增長沒必要要的負擔code
extends
關鍵字實現繼承Object
繼承super.func()
調用父類中的方法。public class Test { TestDemo demo = new TestDemo(); // 代理 public void func() { demo.func(); } } class TestDemo { void func() {} }
finally
代碼塊中。@Override
來表示要重寫父類方法。組合和繼承都容許在新的類中放置子對象,組合是顯式地這樣作,而繼承是隱式地作。對象
繼承很重要可是並不意味着咱們須要經常用他,如何判斷是否應該使用繼承請參照兩個標準:排序
protected
域成員,但最好的方式仍是private
,只有在真正須要的時候才使用protected
關鍵字。final
基本數據類型:表示數據是不可變的常量final
對象引用:引用與對象的關聯關係不可變,但能夠對對象進行操做。final static
約定用大寫字母+下劃線命名規範final
但又未給定初值的域,但能夠在構造方法static
代碼塊或構造器中對final
進行賦值。final
private
方法都隱式的指定是final
的,在private
方法前添加final
是沒有額外意義的。private
修飾的方法,不屬於基類接口一部分,他僅僅是隱藏在類中的一部分代碼。所以若是你在導出類中「覆蓋」了基類的private
方法,其實並無覆蓋private
方法,而產生了一個新方法。final
放在class
前作修飾,代表該類沒法進行繼承final
類中的域和普通類的域並沒有差異final
類隱式的將該類中全部的方法指定爲final
,因此在final
類中給方法添加final
關鍵詞沒有意義。要考慮清楚!!!繼承
每一個類的編譯代碼.class都存在於獨立的文件中,該文件只在須要的使用程序代碼時纔會被加載。接口
static
變量public class Test extends TestParents { // (a) static屬性 static String staticProperty; // (b) 構造方法 public Test() { System.out.println("Test constructor"); } // (c) static代碼塊 { staticProperty = print("Test static property"); System.out.println("Test static"); } // (d) 非static代碼屬性 String property = print("Test property"); public static void main(String[] args) { // (1):System.out.println(Test.staticProperty); // TestParents static property // null(由於static代碼塊中的代碼要建立對象才執行) // (2):Test test = new Test(); // TestParents static property // TestParents property // TestParents static // TestParents constructor // Test static property // Test static // Test property // Test constructor } } class TestParents { static String staticProperty = print("TestParents static property"); String property = print("TestParents property"); { System.out.println("TestParents static"); } public TestParents() { System.out.println("TestParents constructor"); } static String print(String str) { System.out.println(str); return str; } }
static
屬性static
屬性 >> 構造方法;即代碼塊和非static
屬性按照代碼中順序排序,構造函數在最後面public Test() { staticProperty = print("Test static property"); System.out.println("Test static"); property = print("Test property"); System.out.println("Test constructor"); }
優先選擇組合和代理,必要時才使用繼承。內存