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 are in fact a special method, that are used to initialize the state of the newly created instance. When you create an instance like:-

A obj= new A();

Then, the instance of class A is created using new keyword, and then the constructor A() is invoked on that newly created instance.

Further from that article that says: -

Constructors have one purpose in life: to create an instance of a class.

No this is wrong. Constructor don't create instance, its the new keyword that does it. And then constructor initializes the state of the instance created as I stated above.

From JLS - Section 8.8: -

Constructors are invoked by class instance creation expressions (§15.9), by the conversions and concatenations caused by the string concatenation operator + (§15.18.1), and by explicit constructor invocations from other constructors (§8.8.7).

Constructors are never invoked by method invocation expressions (§15.12).

Also from oracle tutorial

Point originOne = new Point(23, 94);

The above statement has three parts (discussed in detail below):

Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
Instantiation: The new keyword is a Java operator that creates the object.
Initialization: The new operator is followed by a call to a constructor, which initializes the new object.

于 2012-10-20T10:12:15.570 回答
0

Constructors are special methods. They are distinct from "normal" methods. But they are methods. Look at this:

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