mardi 28 avril 2015

In Java, how do I call the method of a overridden class from an instance of the overriding class

I am new to Java Inheritance. Please see the code for my parent class called Term:

public class Term {

  public String value;
  public void setValue(String value)
  {
    this.value=value;
  }

  public String getValue()
  {
    return value;
  }

}

Now class OperatorTerm extends Term

public class OperatorTerm extends Term {

  public static Operator type;

  public static boolean equals(String value)
  {
    String regex="(\\++)|(-+)|\\*|/";
    boolean isOperand=value.matches(regex);
    return isOperand;
  }

  public void assignType(String value)
  {
    if(value.equals("+"))
      type=Operator.ADD;
    else if(value.equals("-"))
      type=Operator.SUBTRACT;
    else if(value.equals("*"))
      type=Operator.MULTIPLY;
    else if(value.equals("/"))
      type=Operator.DIVIDE;
    else if(value.equals("++"))
      type=Operator.INCREMENT;
    else
      type=Operator.DECREMENT;
    }
  }

I am creating an OperatorTerm object like this in another class:

public static Term getTerm(String termValue)
{
  Term newTerm=null;
  if(ValueTerm.equals(termValue))
    newTerm=new ValueTerm();
  else if(ReferenceTerm.equals(termValue))
    newTerm=new ReferenceTerm();
  else if(OperatorTerm.equals(termValue))
  {
    newTerm=new OperatorTerm();
  }
  return newTerm;
}

In the last elseif statement, I want to do the following newTerm.assignType. assignType is a method in the OperatorTerm class but it is not present in the Term class. I am unable to do so, and I am wondering if someone can guide me on how can I use newTerm to access the methods of OperatorTerm class

I am creating an object of the overridden class using

Aucun commentaire:

Enregistrer un commentaire