Data, Classes, Inheritance
Inheritance with cupcake and animals example, into project.
public class Quiz extends Generics {
// Class data
public static KeyTypes key = KeyType.title; // static initializer
public static void setOrder(KeyTypes key) { Quiz.key = key; }
public enum KeyType implements KeyTypes {title, Question, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer}
// Instance data
private final String Question;
private final String AnswerA;
private final String AnswerB;
private final String AnswerC;
private final String AnswerD;
private final int CorrectAnswer;
/* constructor
*
*/
public Quiz(String Question, String AnswerA, String AnswerB, String AnswerC, String AnswerD, int CorrectAnswer)
{
super.setType("Quiz");
this.Question = Question;
this.AnswerA = AnswerA;
this.AnswerB = AnswerB;
this.AnswerC = AnswerC;
this.AnswerD = AnswerD;
this.CorrectAnswer = CorrectAnswer;
}
/* 'Generics' requires getKey to help enforce KeyTypes usage */
@Override
protected KeyTypes getKey() { return Quiz.key; }
/* 'Generics' requires toString override
* toString provides data based off of Static Key setting
*/
@Override
public String toString()
{
String output="";
if (KeyType.Question.equals(this.getKey())) {
output += this.Question;
} else if (KeyType.AnswerA.equals(this.getKey())) {
output += this.AnswerA;
} else if (KeyType.AnswerB.equals(this.getKey())) {
output += this.AnswerB;
} else if (KeyType.AnswerC.equals(this.getKey())) {
output += this.AnswerC;
} else if (KeyType.AnswerD.equals(this.getKey())) {
output += this.AnswerD;
} else if (KeyType.CorrectAnswer.equals(this.getKey())) {
output += this.CorrectAnswer;
} else {
output += super.getType() + ": " + this.Question + ", " + this.AnswerA + ", " + this.AnswerB + ", " + this.AnswerC + ", " + this.AnswerD + " | " + this.CorrectAnswer;
}
return output;
}
// Test data initializer
public static Quiz[] Quizes() {
return new Quiz[]{
new Quiz("How many bones are in the human body?", "201", "206", "199", "200", 2),
};
}
/* main to test Animal class
*
*/
public static void main(String[] args)
{
// Inheritance Hierarchy
Quiz[] objs = Quizes();
// print with title
Quiz.setOrder(KeyType.title);
Quiz.print(objs);
// print name only
Quiz.setOrder(KeyType.Question);
Quiz.print(objs);
}
}
Quiz.main(null);