虽然 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 等价物({x: 1, y: 2} 构造 without 使用 new 关键字)。
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 语言编写代码时,它也很容易(并且很容易)违反,所以要记住一些事情(使用简单的结构 会再次困扰你)。