我是Java继承的新手。请参阅我的父类名为Term:
的代码public class Term {
public String value;
public void setValue(String value)
{
this.value=value;
}
public String getValue()
{
return value;
}
}
现在,类OperatorTerm扩展了术语
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;
}
}
我正在另一个类中创建一个这样的OperatorTerm对象:
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;
}
在最后一个elseif语句中,我想执行以下newTerm.assignType。 assignType是OperatorTerm类中的一个方法,但它不存在于Term类中。我无法这样做,我想知道是否有人可以指导我如何使用newTerm来访问OperatorTerm类的方法
我正在使用
创建重写类的对象答案 0 :(得分:3)
#!/usr/bin/python
import sys
# gets list of annotations
def get_annos(infile):
with open(infile, 'r') as fh: # makes sure the file is closed properly
annos = []
for line in fh:
annos.append( line.split('\t')[5] ) # added tab as separator
return annos
# replaces extra info on each header with correct annotation
def add_annos(infile1, infile2, outfile):
annos = get_annos(infile1) # contains list of annos
with open(infile2, 'r') as f2, open(outfile, 'w') as output:
for line in f2:
if line.startswith('>'):
line_split = list(line.split()[0]) # split line on whitespace and store first element in list
line_split.append(annos.pop(0)) # append data of interest to current id line
output.write( ' '.join(line_split) + '\n' ) # join and write to file with a newline character
else:
output.write(line)
anno = sys.argv[1]
seq = sys.argv[2]
out = sys.argv[3]
add_annos(anno, seq, out)
get_annos(anno)
答案 1 :(得分:0)
如果你需要调用方法" newTerm.assignType"在getTerm方法中,也许你只需要返回和/或创建正确的子对象:
public static Term getTerm(String termValue)
{
// Term newTerm=null;
if(ValueTerm.equals(termValue))
return new ValueTerm();
else if(ReferenceTerm.equals(termValue))
return new ReferenceTerm();
else if(OperatorTerm.equals(termValue))
{
OperatorTerm newTerm=new OperatorTerm();
newTerm.assignType("+");
return newTerm;
}
// return newTerm;
}
通常,如果您使用的对象是父对象,则不能使用在扩展类中创建的方法。
希望我的答案对你想做的事情有用。
答案 2 :(得分:0)
else if(OperatorTerm.equals(termValue))
{
newTerm = new Operatorterm();
((OperatorTerm) newTerm).assignType(value);
}
我个人会这样做
else if(OperatorTerm.equals(termValue))
{
OperatorTerm ot = new OperatorTerm();
ot.assignType(value);
return ot;
}
为其他人做同样的事。