雖然Java有一種叫object
的類型,但它不是你想要的。幾乎所有的Java是一個對象,並且有兩種方式來處理這個問題:
定義一個強類型的對象,具有正確的性質,爲一類。 JavaScript有一個類似的概念,實現方式不同,但它應該是可識別的:
public class Car {
private String type;
private int model;
private String color;
public Car(final String type, final int model, final String color) {
this.type = type;
this.model = model;
this.color = color;
}
public String getType() { return this.type; }
public int getModel() { return this.model; }
public String getColor() { return this.color; }
}
final Car car = new Car("Fiat", 500, "white");
// To get the color, you must:
car.getColor();
添加方法來獲取和適當設置屬性,方法啓動,停止,驅動器等
如果你想沒有行爲或限制的財產的鬆散收集,使用Map
。同樣,存在一個Javascript等價物(使用new
關鍵字的{x: 1, y: 2}
構造沒有)。
final Map<String, Object> car = new HashMap<>();
car.put("type", "Fiat");
car.put("model", 500);
car.put("color", "white");
// To get the color, you:
car.get("color");
這種方法的缺點是,編譯器不能執行該類型的對象(幾乎爲好),並在地圖不能有自定義行爲(以任何合理的方式)。在你的例子中,model
是一個數字,但是這將允許你分配任何東西,而不管它是否有意義(也許有人把數據保存在服務器上並使用一個HttpConnection
,你所有的代碼都希望數字爆炸)。
在Java中,如果您知道您擁有多輛汽車,並且具有相同(或類似)屬性,則建議使用第一種方法。它允許編譯器對你知道存在的屬性進行強制和優化,並且繼承允許你稍後添加其他屬性。該類還允許您定義在該實例上運行的方法,這可以幫助在系統的各個部分之間創建抽象(您不需要知道汽車如何啓動,您只需告訴汽車自行啓動)。
僅供參考,JavaScript的等價物分別是:
// #1
var Car = function(type, model, color) {
this.type = type;
this.model = model;
this.color = color;
}
var car = new Car("Fiat", 500, "white");
// #2
var car = {type: "Fiat", model: 500, color: "white"};
// For either option, to get the color you can simply:
console.log(car.color);
我應該站出來最明顯的是Java跟蹤每一個變量是什麼類型。不可見的是,Java會阻止你分配給未知的屬性,比如car.mileage
,其中Javascript會很高興地添加一個新屬性。最後,Java具有可見性的概念,並且默認情況下是私人的(外部觀衆不可見)。在Javascript中複製它看起來像這樣:
var Car = function(type, model, color) {
var _type = type;
var _model = model;
var _color = color;
this.getType = function() { return _type; }
this.getModel = function() { return _model; }
this.getColor = function() { return _color; }
}
console.log(car.getColor());
在Javascript中,您可以利用閉包來隱藏數據。 Java默認隱藏,並且需要您在需要時公開數據。這是一個有趣的選擇,在比較代碼庫時非常相關,並且可以幫助保持相互獨立的類。當你開始用OO語言寫作時,違反也很容易(和誘惑),所以要記住的事情(使用簡單的結構將回來困擾你)。
http://docs.oracle.com/javase/tutorial/java/javaOO/objects.html – adeneo 2014-11-06 17:35:12
在這種情況下,創建一個'Car'類是您可以做的最好的事情。我建議你繼續學習Java編程和OOP。 – 2014-11-06 17:35:58
看看http://stackoverflow.com/a/14442630/203968 – oluies 2014-11-06 17:42:50