【问题标题】:Java: inheritance and overriding methods questionsJava:继承和覆盖方法问题
【发布时间】: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


【解决方案1】:

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

add 方法应该将输入电路添加到影响并联电路的电路列表.

现在它将所有 - “for each” - 从parallel 列表添加到另一个input 电路的电路(全部为0)。哎呀,走错路了!

由于在当前代码中没有将子电路添加到 parallel 列表中,因此 getResistence 中的循环将永远不会真正运行。它返回未更改的 sum 变量中的任何值。

应该对addAll进行类似的更改。

sum 不应该是成员变量;将其保留为局部变量将“修复”修复上一个问题后遇到的另一个问题。

【讨论】:

  • 感谢您的回复!我将 add 方法更改为您的建议并将 sum 变量设为本地,但是我仍然没有得到更新的返回值。
  • @Code.girl 更新后的add 方法中是否还有循环? (不应该。)
  • 哈哈,是的,一旦我从 add 方法中删除了循环,我就让它运行了。非常感谢!
  • 所以,现在我的问题是,当我尝试对系列或并行类使用 add() 方法时,它只会向第一个索引值添加一个值。当我再次调用 add() 方法时,它会将第一个值替换为新值。
  • @Code.girl List.add 从不替换值。因此,一定是其他原因导致了观察到的行为。请记住,创建的每个 new 电路最初都会有 0 个子电路。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-16
  • 2020-07-07
  • 2023-03-07
  • 1970-01-01
  • 2013-08-13
  • 2011-06-14
  • 1970-01-01
相关资源
最近更新 更多