简体   繁体   中英

Under what circumstances should my Java class have a constructor (and not rely on the default constructor)?

I went through a coding problem in a course I'm taking, and I didn't realize that I needed to include my own constructor until I saw the instructor's solution. This has happened a few times throughout the course: I don't expect that I need a constructor, but it turns out I do need one, according to the answer given (below is one of the answers given to me).

I'm wondering now: do I need to make my own constructors when I need to pass parameters and/or I need additional functionality inside the constructor? Are there other situations when relying on the default constructor would be problematic?

    private MenuIterator() {
        menuIterator = menu.iterator();
        calculateNumMenuItems();
    }

You need a constructor exactly when you need to perform some sort of setup for your class and field initialization isn't enough. Your described constructor makes no sense because there's no way for your constructor to get menu (and the private modifier prevents you from calling new MenuIterator() in the usual fashion).

The answer given by chrylis is correct. You may also find this discussion of default constructors useful: Java default constructor . Essentially, if you provide any constructor at all (even a no-arg constructor), you will no longer be provided with a default constructor.

If you need to do anything other than call the class' superclass constructor, you will need to supply your own constructor.

Maybe slightly advanced. In addition to what @chrylis said you also need an explicit constructor if you need the constructor to be anything else than public. This is the case if you want the clients of your class to obtain an instance through a static factory method and not use the constructor directly. The Singleton pattern is just one of many uses of a static method for obtaining an instance.

I wouldn't worry too much. Even though your instructor has a fine solution with a constructor, it could well be that you have a fine solution without a constructor. Programming problems can always be solved in more than one way.

Links

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM