java 通过object修改数据类型_Java中类似JavaScript的Object数据类型?

虽然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 car = new HashMap<>();

car.put("type", "Fiat");

car.put("model", 500);

car.put("color", "white");

// To get the color, you:

car.get("color");

这种方法的缺点是编译器不能强制执行这些对象的类型(几乎也是如此),并且映射不能具有自定义行为(以任何合理的方式).在您的示例中,模型是一个数字,但这将允许您分配任何内容,无论它是否有意义(可能有人将数据保存在服务器上并使用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语言写作时,这也很容易(和诱人)违反,所以要记住一些事情(使用简单的结构会回来困扰你).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值