Skip to content
Advertisement

Printing String Attribute Inherited from SuperClass shows Null

I am extending a class and using the super keyword to in my subclass constructors.

However, when I attempt to print the inherited attribute String. It returns null

public class Question implements IQuestion, Serializable {

private String question;

public Question(String question){
    this.question=question;
}

@Override
public String getQuestion(){
return question;

}

public class TrueFalseQuestion extends Question implements ITrueFalseQuestion{

String question;
boolean answer;

public TrueFalseQuestion(String question, boolean answer){
    super(question);
    this.answer=answer;  
}

@Override
public String getQuestion(){
return question+" True/False?";
}
@Override
public boolean checkAnswer(boolean answer){
    return this.answer==answer;
    
}
}

So when I create a TrueFalseQuestion object and call its getQuestion() method,

I get output: null True/False?

Why is it not printing the question I passed when creating the object? How can I correct this?

Thank you

Advertisement

Answer

That’s coz of the scope of the access modifier on the parent and child classes.

In class Question set the scope of the question variable to something less restrictive. eg

protected String question;

and in the child class, TrueFalseQuestion, remove the variable definition altogether so that the child will reference the parent variable.

String question; // <--- remove this
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement