开发者

Does a constructor have to use all parameters that are passed to it?

Does a constructor have to use all parameters that are passed to it?

For example: if there are three parameters passed to constr开发者_JAVA技巧uct a new object, must all of the parameters be assigned?

Thanks in advance!


Technically no - you do not have to assign all parameters that are passed.

But the more important question is - why pass them on the first place if they are unused?

UPDATE

Let's assume you have this class:-

public final class SomeClazz {
    private final int foo;
    public SomeClazz(int foo,int bar){
        this.foo = foo;
    }
}

And you are invoking it this way:-

SomeClazz clazz = new SomeClazz(2,4);

There is no technical problem with this but as I mentioned above it does not make sense to have a constructor that takes 2 parameters but does not use it. In that case, you should create a constructor that takes just one parameter. Otherwise you are misleading the calling application into thinking that both arguments are being used to create the object.


In general, no. But if you're accepting a parameter and not doing anything with it, why is it there? For example:

class Foo {
    public Foo(int w, int h) {
        width = w;
        height = 10;
    }
    private int width;
    private int height;
}

In the constructor, h is not used. It could be removed from the constructor parameter list.


A constructor, just like any method in Java, does not have to use all its parameters. The call to the constructor, though, needs to supply values for all declared parameters.


A constructor is not required to use all parameters. Not using all parameters raises the interesting question of why they're all not used. This answer assumes you mean that you don't use all of the passed in parameters.


The short answer is no. A constructor, like any method does not have to use everything that is passed to it. However the purpose of a constructor is to "set up" your object, so not using a parameter seems pointless. If you are worried about potentially using a parameter sometimes, overload the constructor.


Of course. In Java, a constructor is a method call, after all; all parameters must have a value.


That will depend of the design of the classes, here is a list of possible repercussions:

1) the constructor will crash and throw and exception 2) the constructor wont crash but when you call a method of the class. 3) the constructor wont crash but you might not be able to assign a value to a property since it is marked as read only.

if you are the owner of the class my advice is too user overloaded constructors.

http://en.wikipedia.org/wiki/Function_overloading

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜