Method and Constructor Overloading in Java - Quiz

Total: 3 questions

1. 

What is method overloading?

Overloaded methods allow you to reuse a method name within a class, but with different parameters (and sometimes with a different return type).

2. 

What is a method signature and why can methods not be overloaded by return type alone?

A method signature is the method name together with the types of its parameters. Signatures must be unique inside a class, and that is exactly what tells overloaded versions apart. The return type is not part of the signature, so void test() and int test() in the same class fail to compile with method test() is already defined. For the same reason methods that differ only by parameter names, by access modifier, by static or final, or by their throws clause do not form an overload. Different return types are allowed only when the parameter lists differ as well.

3. 

How does constructor overloading work in Java and what is the this(...) call for?

Constructors follow the same rules as methods: a class may declare several constructors that differ in the number, type or order of their parameters. When an object is created exactly one of them runs — the one matching the arguments, so new Box(10, 20, 15), new Box() and new Box(7) all reach different versions. To avoid duplicating the initialization logic, one constructor delegates to another with this(...), for example Box() { this(1, 1, 1); }. This is known as constructor chaining, and the this(...) call must be the first statement of the constructor.

Page 1 of 1