*
The moose likes Beginning Java and the fly likes Problem with subclass Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Problem with subclass" Watch "Problem with subclass" New topic
Author

Problem with subclass

Pan Niko
Ranch Hand

Joined: Mar 19, 2011
Posts: 86

Hello,

I have one class Message, which takes as parameter a String. If that String is larger than 50 char, i want to create an element of class BigMessage. Now if also that String is larger than 100 char, i want to throw MessageTooBig Exception. Somewhere i have a mistake, because when trying to run it, i have StackOverfrowException at 5th line of BigMessage.










Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37900
    
  22
You need to draw a diagram, with pencil and paper. Start off with the call to the Message constructor, with a 51 character message. Write down which object is created, then the next line called, and what that line calls and continue. Draw a diagram with a little square for each object created, and keep going until you return from your constructor.

By the way: it's probably StackOverflowError, not "Exception".
Pan Niko
Ranch Hand

Joined: Mar 19, 2011
Posts: 86

Methods called again and again and again...Thank you found it
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

If the actual type is dependent on the parameters, you don't want to use direct constructors. After all, when you call new Message to call the constructor, it creates a Message object always.

In this case I think you want a static factory method. First of all, make the Message constructor protected or give it default access, to prevent it from being called where it shouldn't be. Likewise for the BigMessage constructor. Next, create a static method:
Instead of using "new Message(text)" you now use "Message.createMessage(text)".


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37900
    
  22
Pan Niko wrote:Methods called again and again and again...Thank you found it
Well done
Pan Niko
Ranch Hand

Joined: Mar 19, 2011
Posts: 86

Thank you Rob Spoor
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

You're welcome.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Problem with subclass
 
Similar Threads
doc managment
OOP Modeling - Separate GUI from implementaion-How to refer to class where have more than one method
Create an exception
string reversal problem
Class relations mess - OOP