我对JavaScript有经验,但对Java还不熟悉。在JavaScript中,存在“对象”数据类型,其中给定的变量本质上具有具有自己唯一值的子变量,例如:
var car = {type:"Fiat", model:500, color:"white"};
它几乎像一个数组,但又不完全相同(JavaScript也有数组)。我想知道Java中是否存在相同类型的东西?如果存在,我该如何在Java中声明相同的东西?基于我的搜索,我找不到对象数据类型,但认为可能有类似的东西吗?
我对JavaScript有经验,但对Java还不熟悉。在JavaScript中,存在“对象”数据类型,其中给定的变量本质上具有具有自己唯一值的子变量,例如:
var car = {type:"Fiat", model:500, color:"white"};
它几乎像一个数组,但又不完全相同(JavaScript也有数组)。我想知道Java中是否存在相同类型的东西?如果存在,我该如何在Java中声明相同的东西?基于我的搜索,我找不到对象数据类型,但认为可能有类似的东西吗?
虽然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}
结构,不使用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");
这种方法的缺点在于编译器不能很好地强制实施这些对象的类型,并且在任何合理的方式下,map都无法具有自定义行为。在您的示例中,model
是一个数字,但这将允许您分配任何东西,而不管它是否有意义(也许有人将数据保存在服务器上并使用HttpConnection
,那么所有期望数字的代码都会出现错误)。// #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默认为隐藏,并要求在需要时公开数据。这是一个有趣的选择,在比较代码库时非常相关,可以帮助保持类彼此独立。在开始编写面向对象语言时很容易(也很诱人)违反这一点,因此需要记住一些事情(使用简单的结构体将会回来困扰你)。是的,它们被称为对象并由类定义。这基本上是学习Java时学到的第一件事。
//The definition of an object and it's members
public class Car {
String type, model, color;
}
然后,您可以将它们公开以便在类外访问和更改它们
public class Car {
public String type, model, color;
}
//Create an instance of a Car, point to it with variable c and set one of it's properties/members
Car c = new Car();
c.type = "Fiesta";
但是在Java中,允许外部编辑类的变量被认为是不好的形式,通常你需要添加访问器方法来访问每个变量。
public class Car {
private String type, model, color;
//Return the type of this object
public String getType(){
return type;
}
//Set the type of this object
public void setType(String type){
this.type = type;
}
//etc
}
Car c = new Car();
c.setType("Fiesta");
类是您编写的模板,用于创建对象,它们是类的运行时实例。