3

This question is really confusing

A ________ is a special method that has the same name as the class and is invoked automatically whenever an object of the class is instantiated. Answers:

  • constructor

  • setter

  • getter

  • static method

I was thinking constructor is the only with the same name as the class, but wait! constructor is not really a method, it differs from method. So i read this article and came to a conclusion that this question is wrongly formatted, am I right?

4

2 に答える 2

8

Constructors実際には、新しく作成されたインスタンスの状態を初期化するために使用される特別なメソッドです。次のようなインスタンスを作成する場合:-

A obj= new A();

new次に、キーワードを使用してクラス A のインスタンスが作成さA()れ、その新しく作成されたインスタンスでコンストラクターが呼び出されます。

その記事からさらに: -

コンストラクターには、クラスのインスタンスを作成するという人生の目的が 1 つあります。

いいえ、これは間違っています。コンストラクターはインスタンスを作成しません。それを行うnewキーワードです。そして、コンストラクターは、上で述べたように作成されたインスタンスの状態を初期化します。

からJLS - Section 8.8: -

コンストラクターは、クラス インスタンス作成式 (§15.9)、文字列連結演算子 + (§15.18.1) による変換と連結、および他のコンストラクターからの明示的なコンストラクター呼び出し (§8.8.7) によって呼び出されます。

コンストラクターは、メソッド呼び出し式によって呼び出されることはありません (§15.12)。

また、オラクルのチュートリアルから

ポイント originOne = 新しいポイント(23, 94);



上記のステートメントには 3 つの部分があります (以下で詳しく説明します) 。
Instantiation : new キーワードは、オブジェクトを作成する Java オペレーターです。
初期化: new 演算子の後には、新しいオブジェクトを初期化するコンストラクターへの呼び出しが続きます。

于 2012-10-20T10:12:15.570 に答える
0

コンストラクターは特別なメソッドです。それらは「通常の」方法とは異なります。しかし、それらは方法です。これを見てください:

public class A {    
    public A() {
        this(5); // calls A(int)
    }        
    public A(int arg) {
        // ...
    }        
}
于 2012-10-20T10:23:31.363 に答える