Returning Objects

A method can return any type of data, including class types. For example, the class ErrorMsg shown here could be used to report errors. Its method, getErrorMsg( ), returns a String object that contains a description of an error based upon the error code that it is passed.

Image

You can, of course, also return objects of classes that you create. For example, here is a reworked version of the preceding program that creates two error classes. One is called Err, and it encapsulates an error message along with a severity code. The second is called ErrorInfo. It defines a method called getErrorInfo( ), which returns an Err object.

Get Java, A Beginner's Guide, 5th Edition, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.