Now, let's turn to the implementation of the display method. It's supposed to
display a choice question in this format. First, the text of the question. Then
all of the choices, and we put a 1, 2, 3, 4 in front of each of the choices in
case the poor test taker is too frazzled to figure out the numbers themselves.
It's easy enough to do this part. All we have to do is loop through the choices
and print them with a number in front of them. And since this has nothing to do
with learning about inheritance, I'm just going to give you this code. It's
right here. So we print the number of the ith choice and the ith item. actually
not quite because in Java the choices have indexes, zero, one, two, and three.
And we chose the more traditional one, two, three, four, which accounts for the
i plus 1 over here. The hard part is to display the text of the question. And
again, the question text is in the Superclass object, and we can't get at it
directly. Let's have a look at the Super class. Here is the question text, do
we have any method that lets us read it? there is, And we could call display,
and then it would print it. That's just what we need. Lets do it. Here I call
display that should display the text and then here I am displaying these
choices around the demo. Oh! something very bad happened, I got a
StackOverflowError. Now, that's technical lingo for having a method that
keeps calling itself. why itself? See the method is called display and here it
calls itself. That's a problem, I didn't want to call my own method, I wanted
to call the display method of the Question class. So my difficulty is that I
have two methods called display in the Superclass and in the Subclass. And they
have the same name. That's exactly what always happens when you override a
method. Now, there's a special syntax for invoking the Superclass method and it
looks like that. You simply say super.display. Go ahead and give that a try and
fix up the display method.
Ahora, pasemos a la implementación del método display. Se supone que
muestra una pregunta de opciones en este formato. Primero, el texto de la pregunta. Luego
todas las opciones, y ponemos un 1, 2, 3, 4 frente a cada una de las opciones en
el caso que un pobre tomador de prueba esté demasiado agotado para averiguar los números él mismo.
Esta parte es bastante fácil de hacer. Todo lo que tenemos que hacer es ir en bucle por las opciones
e imprimirlas con un número delante de ellas. Y como esto no tiene nada que ver
con aprender más sobre herencia, sólo voy a darte este código. Está
justo aquí. Así que imprimimos el número de la opción i’ésima y el artículo i’ésimo. En realidad
no es del todo así, ya que en Java las opciones tienen índices, cero, uno, dos y tres.
Y elegimos el más tradicional uno, dos, tres, cuatro, lo que explica la
i más 1 por aquí. La parte difícil es mostrar el texto de la pregunta. Y
de nuevo, el texto de la pregunta está en el objeto Superclase y no podemos llegar a él
directamente. Veamos esta Superclase. Aquí está el texto de la pregunta, ¿contamos
con algún método que nos permite leerlo? No hay ninguno. Ah, pero podríamos llamar a display
y entonces lo imprimiría. Eso es justo lo que necesitamos. Vamos a hacerlo. Aquí llamo a
display que debe mostrar el texto y después aquí estoy mostrando estas
opciones. Voy a ejecutar la demostración. ¡Oh! algo muy malo ha pasado, recibí un
StackOverflowError. Ahora, esto es jerga técnica para tener un método que
sigue llamándose a sí mismo. ¿Por qué a sí mismo? Observa que el método se llama display y aquí se
llama a sí mismo. Eso es un problema, no quería llamar a mi propio método, quería
llamar al método display de la clase Pregunta. Así que mi dificultad es que
tengo dos métodos llamados display en la Superclase y en la Subclase. Y estos
tienen el mismo nombre. Eso es exactamente lo que siempre sucede cuando se sobrescribe un
método. Ahora, hay una sintaxis especial para invocar el método de la superclase y
se parece a eso. Simplemente dices super.display. Sigue adelante e inténtalo y
arregla el método display.
Passons maintenant à l'implémentation
de la méthode Display.
Il est censé afficher une question
de choix dans ce format.
D'abord, le texte de la question.
Ensuite, tous les choix,
et nous mettons un 1, 2, 3, 4
en face de chacun des choix au cas où
le pauvre testeur est trop fatigué
pour comprendre les chiffres.
C'est assez facile de faire cette partie.
Tout ce qu'il faut faire
c'est parcourir les choix
et les imprimer avec un numéro devant.
Et comme ça n'a rien à voir
avec l'apprentissage de l'héritage,
je vais juste vous donner ce code.
C'est ici.
Nous imprimons donc le numéro
du ième choix et le ième élément.
en fait pas tout à fait parce que
dans Java les choix ont des index,
0, 1, 2 et 3.
Et nous avons choisi le plus
traditionnel, 1, 2, 3, 4,
ce qui explique le i + 1 ici.
Le plus dur est d'afficher
le texte de la question.
Là encore, le texte de la question
est dans l'objet Superclass
et nous ne pouvons pas
y accéder directement.
Jetons un coup d’œil à Superclass.
Voici le texte de la question, avons-nous
une méthode qui nous permet de le lire?
il y a,
nous pourrions appeler Display
et ensuite il l'imprimerait.
C'est juste ce qu'il nous faut.
Faisons le.
Ici, j'appelle Display qui
devrait afficher le texte,
puis ici, je montre ces choix
autour de la démo.
Oh! Quelque chose de très
mauvais est arrivé,
j'ai eu un StackOverflowError.
C'est du jargon technique
pour avoir une méthode
qui ne cesse de s'appeler.
Pourquoi elle-même?
Vous voyez que la méthode
s'appelle Display
et ici elle s'appelle elle-même.
C'est un problème, je ne voulais pas
appeler ma propre méthode,
je voulais appeler la méthode
Display de la classe Question.
Donc mon problème est que j'ai deux
méthodes appelées display
dans la super-classe et
dans la sous-classe
et elle ont le même nom.
C'est exactement ce qui se passe
lorsque vous remplacez une méthode.
Il y a une syntaxe spéciale
pour appeler la méthode Superclass
et ça ressemble à ça.
Vous dites simplement super.display.
Allez-y, essayez et corrigez
la méthode Display.
ではdisplayメソッドの実装を始めましょう
このメソッドは選択問題をこの形式で表示します
最初は質問文で
次にすべての選択肢です 解答者が答える際に
迷わないように各選択肢の前に
1、2、3、4と振っておきます
この部分の処理はとても簡単です
選択肢をループで回して
その前に番号を出力するだけです
これは継承の学習とは
無関係なのでこのコードをお見せします これです
i番目の選択肢の番号と中身を出力します
番号とiはまったく同じではありません
Javaでchoicesのインデックスは
ゼロ、1、2、3だからです
より一般的な1、2、3、4としたいので
ここはi + 1とします
難しいのは質問文を表示する部分です
質問文textは
スーパークラスのオブジェクト内にあるので
直接得ることはできません
スーパークラスを見てみましょう
これが質問文textです
これを表示させるメソッドを探します
このdiplayメソッドを呼び出せば
質問文textを出力できます
これが欲しかったものです 実行してみましょう
質問文textを表示するdisplayメソッドを呼び出し
choicesを表示させます デモを実行すると
非常に悪いことが起こりました
スタックオーバーフローエラーといって
再帰呼び出しを続けるメソッドの技術用語です
なぜ再帰になったのでしょう
displayというメソッド内でdisplayメソッドを
呼び出しています これが問題です
呼び出したかったのは自身のメソッドではなく
Questionクラスのdisplayメソッドです
問題なのはdisplayというメソッドが
同じ名前でスーパークラスとサブクラスの
両方にあるということです
メソッドをオーバーライドする際よく起きます
スーパークラスのメソッドを呼び出すための
特別な構文があります
これが例文です
単にsuper.display()と書きます
ではdisplayメソッドを修正してください
이제 display 메소드를 구현해보겠습니다. 이 형식으로
선택 질문을 출력해야 하고, 첫 번째로 질문의 텍스트를 출력하고
1, 2, 3, 4 선택지를 모두 출력합니다. 숫자를 넣은 이유는, 테스터가
구분 못할 수도 있는 상황을 대비해서 넣은 겁니다.
이 부분은 하기 쉽습니다. 그저 반복문으로 번호를
출력하면 됩니다. 그리고 이는 상속과 관계없는
일이라서 여러분에게 코드를 그냥 주겠습니다. 여기에 있습니다.
i 번째 선택지와 i번째 요소를 출력합니다. 확실히 i번째로
하지는 않습니다, 왜냐하면 자바는 인덱스가 0부터 시작해서 입니다.
그래서 여기서 i에 1을 더하게 됩니다.
어려운 부분은, 질문의 텍스트를 출력하는 것입니다.
질문의 텍스트는 슈퍼 클래스의 객체입니다. 그리고 직접적으로
가져올 수 없습니다. 슈퍼 클래스를 봅시다. 이 변수가
질문 텍스트입니다. 이를 읽어줄 수 있는 메스도가 있나요? display를
호출하고 출력하면 됩니다. 필요한 것을 찾았으니 해봅시다. 여기서
display를 호출하면 텍스트를 출력하게 되고 여기에 선택지들을
모두 출력합니다. 오! 되게 안 좋은 일이 생겼군요. 스택 오버플로우가
생겨버렸군요. 이는 바로 메소드가 자기 자신을 계속 부르는
형태를 말합니다. 왜 자기 자신일까요? 이 메소드는 display입니다.
자기 자신을 부르죠. 그게 문제입니다. 여기 안에 있는 메소드가 아닌
Question 클래스에 있는 display를 호출하고 싶습니다. 이 상황은 바로
슈퍼 클래스와 서브 클래스에 같은 이름의 메소드가 있어서 문제가 된 겁니다.
메소드를 덮어쓸 때 꼭 이러한 일이 일어납니다.
이를 해결해주는 특별한 문법이 있습니다.
간단하게 super.display()를 하시면 됩니다. 이를 이렇게
해보시고 프로그램을 고쳐보세요.
Giờ thì chuyển sang phần thêm display method. Giả sử là
để hiển thị một choice question trong định dạng như này. Trước tiên là text của câu hỏi.
Tiếp theo là tất cả các lựa chọn. Và ta thêm các số 1, 2, 3, 4 vào trước
mỗi lựa chọn để dễ phân biệt hơn.
Phần này thì cũng dễ. Ta chỉ việc lặp qua mảng các lựa chọn
và in chúng ra, với một con số ở trước. Và vì cái này không có liên quan gì
tới việc học về inheritance (kế thừa), tôi sẽ đưa cho bạn đoạn code này.
Nó ở đây. Nên ta in ra số của lựa chọn và lựa chọn đó.
Trong Java, các lựa chọn được đánh số là 0, 1, 2, 3.
Và ta thì muốn là 1, 2, 3, 4, nghĩa là tính bằng
i + 1 như trên đây. Phần khó là hiển thị text của câu hỏi.
Và, question text thì ở trong Superclass object, và ta không thể
lấy nó trực tiếp. Hãy xem Superclass. Đây là question text,
ta có method nào để đọc nó không? có đó. Và ta có thể gọi display,
và sau đó nó sẽ in ra. Đó là thứ ta cần. Hãy làm thế.
Ở đây tôi gọi display, nó sẽ hiển thị text và sau đó tôi có thể hiện thị
các lựa chọn này. Oh, có điều gì đó không ổn ở đây,
tôi có lỗi StackOverflow Error. Đó là do có một method
mà gọi chính nó. Sao lại là chính nó. Xem method đang gọi display,
và ở đây nó đang gọi chính nó. Đó là vấn đề, tôi không muốn gọi method của tôi,
tôi muốn gọi display method của Question class cơ mà. Nên, vấn đề khó khăn là,
có 2 method gọi là display, ở trong Superclass và ở subclass này.
Và tên của nó giống nhau. Đó chính là vấn đề luôn xảy ra khi ta override một method.
Giờ, có một cấu trúc đặc biệt để gọi Superclass method,
và nó như này. Bạn đơn giản ghi là super.display() Tiếp tục và thử nó
và sửa lỗi trong display method.