Java:继承和重写方法问题

时间:2015-09-20 05:12:23

标签: java inheritance methods override

我目前正在处理我的java教科书中的一个问题,该问题围绕创建一个Circuit超类和一个Resistor,Serial和Parallel子类。 Serial和Parallel类具有ArrayLists,它们应该由Circuit类的对象填充。每个子类都包含一个getResistance()方法,该方法应该覆盖超类中的getResistance()方法。我的问题是无论输入如何,只更改实例变量" sum"从Parallel类更新getResistance()的结果。

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);  

  }
  }

1 个答案:

答案 0 :(得分:1)

与继承或覆盖无关(它改变了sum变量没有效果),而是;

add方法应该将输入电路添加到危害并联电路的电路列表< /强>

现在它为每个&#34;添加所有 - &#34; - 从parallel列表到另一个input电路的电路(全部为0)。哎呀,错误的方式!

因为在当前代码中没有向parallel列表添加子循环,getResistence中的循环将永远不会运行..这将返回未更改的sum变量中的任何值。 / p>

应对addAll进行类似的更改。

sum不应该是成员变量;保持它是一个局部变量将修复&#39;修复上一期后遇到的另一个问题。