下面的代码会打印什么? Java的

时间:2017-09-05 22:43:35

标签: java

这是一个我已经坚持了一段时间的作业的问题。我必须写下该程序的输出是什么,我希望我能找到一些解释来清除我的困惑。

class Derp { 

    public int x;

    /* this method doesn't have any return type so the 
        program shouldn't even run? I get errors even when i 
        typed it netbeans. I decided to assume it was a 
        mistake made by the professor*/
    public Derp(int x) { 
      this.x=x; 
    }

    public String toString() {
      return new String("x=" + x);
    }
}

public class WhatsPrinted06 {

    public static void func(Derp d) {
      d.x++;  

    /* i don't think i've ever seen something like this, i tried 
        typing it in netbeans but i get an error. Is this another 
        way of writing d+=x;? It still shows an error 
        however*/
      System.out.println(d);
    }

    public static void main(String args[]) {
      Derp d1 = new Derp(10);
      func(d1);
    }

经过这个,我以为教授可能会试图看看我们是否可以弄清楚程序何时运行,但是在其他问题上d.x ++不断出现,她仍然没有在其他问题中为公共Derp {}添加返回类型。

1 个答案:

答案 0 :(得分:0)

代码显然打印x = 11.

没有返回类型的方法是构造函数,即在实例化对象时调用的特殊方法。