"What is the correct declaration for an abstract method 'add' in a class that is accessible to any class, takes no arguments and returns nothing?"
The correct answer is;
Why is it necessary to write "throws Exception"? I think I could declare this class without writing "throws Exception" and it would compile. Why is "throws Exception" required in this case? Also, does anyone know when a class with these constraints would be used? From what I understand, it can't be constructed (allocated memory in an object) because it is abstract, and it takes no arguments and returns nothing. To me this is a weird method and I can only think of using it in some other subclass by overriding it. All thoughts are welcome!
- the method should be abstract
- the method should be public ("accessible to any class")
- the method should have an empty parameter list ("takes no arguments")
- the method should be void ("returns nothing")
Nothing in the question says anything about exceptions, so the "throws Exception" is not required.
Since the method is abstract, it can only be declared in an interface or in an abstract class. To be able to call it, you would need to have a non-abstract class that implements the interface, or the abstract class in which the method is declared. That non-abstract class would have to override the method and provide an implementation.
Maneesh Godbole wrote:
This is the first time I am seeing a method declared this way.
I couldn't agree more Maneesh. Putting the visibility keyword first is the coding standard I have always seen. It makes me question the quality of the enthuware testing suite I purchased. I listed the question and answer verbatim.
Is the a result of Testing Driven Development or a more complete way to write methods? Also, can anyone think of an example situation where a method like this would be used? I guess when it is needed by an interface or an abstract class, right? I just have little experience and I am having trouble visualizing when I would use something like this.
John Pacuta wrote:Is the a result of Testing Driven Development or a more complete way to write methods?
No, this does not really have anything to do with TDD and you should not add "... throws Exception" just for "completeness".
In fact, in my opinion it is bad practice to declare that a method can throw any kind of exception like this. It forces the caller of this method to catch Exception (= catch all possible exceptions), which is a bad practice.
If a method might throw one or more specific kinds of checked exceptions, then it should specify those in a "throws" declaration. But it should only specify the specific kinds of exceptions it can throw, and not an overly broad class such as Exception.
For example, if the method does I/O, it might declare that it can throw IOException.