我目前正在研究一个围绕创建Circuit超类和Resistor,Serial和Parallel子类的java教科书中的问题。串行和并行类有ArrayLists,应该由Circuit类的对象填充。每个子类都包含一个getResistance()方法,该方法应该覆盖超类中的getResistance()方法。我的问题是,无论输入如何,只需从Parallel类更改实例变量“sum”即可更新getResistance()的结果。Java:继承和重载方法问题
P.S.我知道这是学校工作,我不希望任何人“为我做功课”,但我仍然在学习继承,并想知道我做错了什么,以备将来参考。
这里是我的主类:
public class Circuit
{
//this is the superclass and acts just as a container class
public double getResistance()
{
//I want this method to take an arbitrary value and return it.
return 0;
}
public void add(Circuit input)
{
//this method is supposed to add a value to an object of the Circuit class
}
public void addAll(ArrayList<Circuit>circuits)
{
//this method is for combining ArrayList and takes in ArrayList
}
}
并行的子类:
//subclass of Circuit superclass
public class Parallel extends Circuit
{
//this instance variable is of the Circuit class
private ArrayList<Circuit> parallel = new ArrayList<>();
private double resistance;
private double sum;
public void add(Circuit input)
{
//int count = 0;
//adding values to populate ArrayList
for(Circuit x: parallel)
{
//setting the xth index value to the value to the input
x.add(input);
//count++;
}
}
public double getResistance()
{
//this method overrides the one from the superclass
//we are the sum of the input resistances of the ArrayList
if(parallel.size()> 0)
{
for(Circuit x: parallel)
{
resistance = x.getResistance();
sum=+ 1/resistance;
}
}
return sum;
}
public void addAll(Serial series)
{
//this method is supposed to add the ArrayList of the Circuit type together
series.addAll(parallel);
}
}
第一组代码应该是我的超类,而不是主类! –