我來自JavaScript和Node.js背景,儘管我擁有大部分的OOP基礎知識,但還是有許多我不太瞭解的Java基礎知識。例如,我正在做a Spring tutorial,並立即遇到了一些令我困惑的語法。爲什麼在Java中的類實例中返回一個類實例?
第一次演練是一個hello world應用程序。首先,我們建立了一個問候類:
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
首先,我不明白爲什麼他們定義的類本身內部的類的實例開始。爲什麼不爲公共課添加參數?無論如何,那不是我的問題。當我得到更多的損失是,當我們做一個問候控制器:
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
// This ensures that HTTP requests to /greeting are mapped to the greeting() method.
@RequestMapping("/greeting")
public Greeting greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(),
String.format(template, name));
}
}
在這個文件時,我就拿到public Greeting greeting
創建問候語類的新實例,但它只有一個參數時,構造函數有兩個,long id
和String content
。接下來,他們返回該類的另一個實例,這次使用與構造函數結構相匹配的參數。
這是爲什麼?
_define類中的類的一個實例本身_你在哪裏看到這個?另外,如果這不是您的問題或與此相關,請將其刪除。 –
_'''Public Greeting greeting'創建Greeting類的新實例_否,它不。這只是一個返回類型爲「Greeting」的方法。 –
「但它只有一個參數,當構造函數有兩個」 - 不是另一個參數「String.format(...)」? (看起來像逗號被用來代替該行上的點) – BretC