【发布时间】:2015-09-20 05:12:22
【问题描述】:
我目前正在研究我的 java 教科书中的一个问题,该问题围绕创建一个 Circuit 超类和一个 Resistor、Serial 和 Parallel 子类。 Serial 和 Parallel 类具有应该由 Circuit 类的对象填充的 ArrayList。每个子类都包含一个 getResistance() 方法,该方法应该覆盖超类的 getResistance() 方法。我的问题是,无论输入如何,只有从 Parallel 类更改实例变量“sum”才会更新 getResistance() 的结果。
附:我知道这是学校作业,我不希望任何人“为我做作业”,但我仍在学习继承,并想知道我做错了什么以供将来参考。
这是我的主要课程:
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);
}
}
【问题讨论】:
-
第一组代码应该是我的超类,而不是主类!
标签: java inheritance methods overriding