• Post Reply Bookmark Topic Watch Topic
  • New Topic

Polymorphism exercise  RSS feed

 
andy colins
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
so there is this piece of code:



as you can see, if youll copy it to eclipse it will give the result 13.
but i failed to understand why :/
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where does that code come from? Please always tell us to avoid copyright problems.

You have some confusing code there. It looks like the sort of thing they write in exam books. Remember there are several variables called x which might all have different values.
Start by putting some debugging code in those two constructors and the 4 methods, e.g. System.out.println("In A constructor. x = " + x);
Then you will be able to follow the flow of control through the application.
 
andy colins
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
no worries. it's from an exam i have found online . available for all .
and how do i debug this code in efficient way? i have never done this before
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You put that sort of print call in every method, along with the values of any variables changed by that method. Then it will tell you where you are in the objects, i.e. which method.

And please tell us which online exam it is.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow, that's a convoluted piece of code. It took a fair amount of mental effort to do that in my head.

As well as adding debug statements like Campbell suggests it may be worth your while sitting down with a pencil and paper beforehand and writing down what order you think the methods/constructors get called and what values they return etc. You can then compare your prediction with the debug statements to see if you were right.
 
Campbell Ritchie
Marshal
Posts: 56578
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I had though to get the printouts first and then consider the pencil and paper. You will learn a lot from doing it pencil first.

And it isn't pencil and paper. It is pencil paper and eraser. The latter is very important
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!