《JAVA編程思想》學習備忘(第155頁:Initialization & Cleanup)--1

As the computer revolution progresses,"unsafe" programming has become one of the major culprits that makes programming expensive.
隨着電腦革命的進展,“非安全的”編程成爲“昂貴”編程的主要原兇。
 
Guaranteed initialization with the constructor
In Java,the class designer can guarantee initialization of every object by providing a constructor.If a class has a constructor,Java automatically calls that constructor when an object is created,before users can even get their hands on it.So initialization is guaranteed.
構造方法與類名相同。
無參的構造方法叫做默認構造方法。
構造方法沒有返回值。
 
Method overloading
方法重載。同一個詞表達不同的意思叫重載。
構造方法重載與方法重載的例子:
import static staticPrint.Print.print;
class Tree{
    int height;
    Tree(){
        print("Planting a seedling");
        height = 0;
    }
    Tree(int initialHeight){
        height = initialHeight;
        print("Creating new Tree that is " + height + " feet tall");
    }
    void info(){
        print("Tree is " + height + " feet tall");
    }
    void info(String s){
        print(s + ": Tree is " + height + " feet tall");
    }
}
public class Overloading{
    public static void main(String[] args){
        for(int i = 0; i < 5; i++){
            Tree t = new Tree(i);
            t.info();
            t.info("overloaded method");
        }
        //Overloaded constructor;
        new Tree();
    }
}
試運行以上程序。
 
Distinguishing overloaded methods
每個重載的方法必須帶一個獨特的參數類型列表,或參數列表順序不同。纔可區分開來。
 
Overloading with primitives
A primitive can be automatically promoted from a smaller type to larger one,(針對書中的例子,原釋:)the constant value 5 is treated as an int,so if an overloaded method is available that takes an int,it is used.In all other cases,if you hava a data type that is smaller than the argument in the method,that data type is promoted.char produces a slightly different effect,since if it doesn't find an exact char match,it is promoted to int.
What happens if your argument is bigger than the argument expected by the overloaded method?(針對書中例子的原釋:)Here,the methods take narrower primitive values.If your argument is wider,then you must perform a narrowing conversion with a cast.If you don't do this,the compiler will issue an error message.
 
Overloading on return values
you cannot use return value types to distinguish overloaded methods.
 
Default constructors
如果類中沒有任何構造方法,編譯器將會自動爲你創建一個默認構造方法;如果你定義了任何構造方法,編譯器將不會爲你合成一個默認構造方法。 
 
(待續)
 
發佈了31 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章