【问题标题】:Java Program causes infinite loopJava程序导致无限循环
【发布时间】:2016-08-20 07:22:59
【问题描述】:

这是我的 Java 代码。我用两个类创建了一个接口abc。 a1 类实现接口abc。 b1类使用接口函数display显示一些数据。

a1 类在无限循环中运行。

interface abc
{
  display(String s);
}

class a1 implments abc
{
   a1(b1 obj)
  {
  }
    public void display(String s)
    {
        System.out.println(s);
    }
}

class b1
{
    abc abc1;
    private xyz x;
    b1(xyz xyz1)    //xyz is interface
    {
           this.x = xyz1; 
    }
    public void show()
    {
          abc1 = new a1(new b1(this.x));   //  here is problm.. this statement cause infinite loop.
          String str = "Hello"; 
          abc1.display(str);
    }
}

该程序导致类a1 的无限循环。 请找出问题并帮我解决。

【问题讨论】:

  • 你试过使用调试器吗?
  • 这个程序没有错误。但会导致无限循环。
  • 其实有错误。你拼错了“implements”,忘记了display声明开头的void
  • 你能不能也给你的主课?看来您正在创建一个不可能的接口对象
  • 你在那里有循环依赖...... a1 真的需要 b1 对象吗?

标签: java class interface


【解决方案1】:

它没有无限循环。 我创建了一个名为 b1.show 的 main,它运行成功。

interface abc
{
   void display(String s);
}

class a1 implements abc
{  
   a1(b1 obj)
  {
}
  public void display(String s)
  {
     System.out.println(s);
  }
}

class b1
{
   abc abc1;
   private xyz x;
   b1(xyz xyz1)    //xyz is interface
   {
       this.x = xyz1; 
}
    public void show()
    {
        abc1 = new a1(new b1(this.x));   //  here is problm.. this statement cause infinite loop.
        String str = "Hello"; 
        abc1.display(str);
   }
}
public class Main{
    public static void main(String args[]){
      xyz xyz1 = null;
        b1 objb1=new b1(xyz1); 
      objb1.show();
      System.out.println("out of all classes..");
  }

}

interface xyz{

}

【讨论】:

    猜你喜欢
    • 2014-12-16
    • 2016-02-06
    • 2012-05-09
    • 2020-08-27
    • 2021-05-07
    • 2012-08-24
    • 2020-11-16
    • 1970-01-01
    相关资源
    最近更新 更多