2015-09-20 85 views
1

我目前正在研究一个围绕创建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); 

    } 
    } 
+0

第一组代码应该是我的超类,而不是主类! –

回答

1

无关,与继承或重载(它,它正在改变sum变量没有任何作用),而;

add方法输入电路添加到电路妥协并联电路的列表。

现在,它将从parallel列表中的所有电路(全部0个)中的所有电路(其中每个都加上“0”)加到其他input电路中。哎呀,错误的方式!

由于在当前代码中没有将子电路添加到parallel列表中,所以getResistence中的循环永远不会实际运行..它会返回不变的sum变量中的任何值。

addAll应作类似更改。

sum不应该是一个成员变量;保留一个局部变量将会修复在解决上一个问题后遇到的另一个问题。

+0

感谢您的回复!我将add方法更改为您的建议,并将sum变量作为本地变量,但我仍未获得更新的返回值。 –

+0

@ Code.girl更新后的'add'方法是否还有一个循环? (它不应该) – user2864740

+0

哈哈,雅我得到它运行一旦我从添加方法中删除循环。非常感谢你! –