《JAVA编程思想》学习备忘(第155页:Initialization & Cleanup)--1

来源:互联网 发布:finale打谱软件休止符 编辑:程序博客网 时间:2024/05/22 17:37
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
如果类中没有任何构造方法,编译器将会自动为你创建一个默认构造方法;如果你定义了任何构造方法,编译器将不会为你合成一个默认构造方法。 
 
(待续)
 
原创粉丝点击