开发者

What is the difference between an "Accessor method" and a "constructor"?

What is the difference between "Accessor method" and a "cons开发者_JAVA百科tructor"?


Constructors initialize a new object. Accessors allow an external caller to obtain information about the state of an object.


A constructor is a function responsible for object initialization. It is called when a new instance of a class is created (statically or dynamically using new) and it allows you to explicitly initialize internal attributes of an object or to execute arbitrary code. It is complemented by the destructor, which is called automatically when an object is deallocated (immediately before deallocation). An example is a class that has a pointer to an array; in the constructor, you would allocate the array, and in the destructor you free the memory allocated in the constructor.

An accessor method (or a getter) is a method that allows you to access internal attributes of an object. It is used in tandem with a setter to encapsulate certain attributes of an object. The accessor should be immutable (that is, it should not affect the internal state of the object).

Note that, excerpt the destructor, all the methods of a class can be overloaded, including the constructor. A constructor that takes a const reference of an object of the same class is called a copy constructor. As the default constructor, this is generated automatically by the compiler, and by default, it copies all the attributes, field by field. As this behavior is not always wanted, you can implement the copy constructor to be able to properly copy another object (or to stop copying - see boost::noncopyable).

Example:

// C++
class Foo {
    int i;

public:
    // Copy constructor
    Foo(const Foo& foo) {
        this->i = foo.i;
        // Here you can do other stuff, beside raw copying...
    }
};

class Bar {
public:
    // Constructor
    Bar() {
        m_foo = new Foo();
    }

    // Destructor
    ~Bar() {
        delete m_foo;
        m_foo = 0;
    }

    // Getter (hides the actual attribute)
    const Foo* getFoo() const { return m_foo; }

    // Setter
    void setFoo(Foo* foo) {
        // Create a copy of Foo
        m_foo = new Foo(*foo);
    }

private:
    Foo* m_foo;
};


Constructor is a block of code, which runs when you use new keyword in order to instantiate an object. http://beginnersbook.com/2013/03/constructors-in-java/

A accessor method is used to return the value of a private field. It follows a naming scheme prefixing the word "get" to the start of the method name. http://java.about.com/od/workingwithobjects/a/accessormutator.htm

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜