English subtitles

← The Display Method - Intro to Java Programming

Get Embed Code
6 Languages

Showing Revision 6 created 09/10/2017 by Dejan Trajkovic.

  1. Now, let's turn to the implementation of the display method. It's supposed to
  2. display a choice question in this format. First, the text of the question. Then
  3. all of the choices, and we put a 1, 2, 3, 4 in front of each of the choices in
  4. case the poor test taker is too frazzled to figure out the numbers themselves.
  5. It's easy enough to do this part. All we have to do is loop through the choices
  6. and print them with a number in front of them. And since this has nothing to do
  7. with learning about inheritance, I'm just going to give you this code. It's
  8. right here. So we print the number of the ith choice and the ith item. actually
  9. not quite because in Java the choices have indexes, zero, one, two, and three.
  10. And we chose the more traditional one, two, three, four, which accounts for the
  11. i plus 1 over here. The hard part is to display the text of the question. And
  12. again, the question text is in the Superclass object, and we can't get at it
  13. directly. Let's have a look at the Super class. Here is the question text, do
  14. we have any method that lets us read it? there is, And we could call display,
  15. and then it would print it. That's just what we need. Lets do it. Here I call
  16. display that should display the text and then here I am displaying these
  17. choices around the demo. Oh! something very bad happened, I got a
  18. StackOverflowError. Now, that's technical lingo for having a method that
  19. keeps calling itself. why itself? See the method is called display and here it
  20. calls itself. That's a problem, I didn't want to call my own method, I wanted
  21. to call the display method of the Question class. So my difficulty is that I
  22. have two methods called display in the Superclass and in the Subclass. And they
  23. have the same name. That's exactly what always happens when you override a
  24. method. Now, there's a special syntax for invoking the Superclass method and it
  25. looks like that. You simply say super.display. Go ahead and give that a try and
  26. fix up the display method.