Hello, In the following code segment 2, I do not know why class B is put inside method dest rather than outside the method (in code segment 1). Could anyone tell me what is the purpose of putting class inside method ? Is it better than put it outside the method ? Thx!
Example 2 illustrates what is known as a local class. It can only be instantiated from within the dest() method. Since the method returns a reference to C, the calling method can use the object as if it is a C. However, it cannot cast it to a B since that class delcaration is unavailable. As for which way is better, it depends on the design constraints. In fact, this is the answer for most similar questions in programming. Understanding the different ways you can declare a class will help you decide which fits a certain set of design criteria.