Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Problem with subclass

 
Pan Niko
Ranch Hand
Posts: 86
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49729
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 86
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Methods called again and again and again...Thank you found it
 
Rob Spoor
Sheriff
Pie
Posts: 20605
60
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)".
 
Campbell Ritchie
Sheriff
Pie
Posts: 49729
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Pan Niko wrote:Methods called again and again and again...Thank you found it
Well done
 
Pan Niko
Ranch Hand
Posts: 86
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Rob Spoor
 
Rob Spoor
Sheriff
Pie
Posts: 20605
60
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic