覆盖赋值运算符 [英] Overriding assignment operator

查看:123
本文介绍了覆盖赋值运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中是否存在这样的事情?例如,我总是可以这样做:

Does such a thing exist in Java? For example, I can always do something like:

AJSDate startDate = new AJSDate("20090811");

但我宁愿把它作为:

but I would rather have it as:

AJSDate startDate = "20090811";


推荐答案

不,你不能这样做在Java中。这是Gosling等人的慎重选择。因为这个语言的原始设计目标之一是简单和透明:你应该总是知道代码只是通过查看它,没有隐藏效果。 (简单和Java,哦世界如何变化。)

你可以做的是设置一个静态的工厂方法,例如:



No, you cannot do this in Java. It was a deliberate choice by Gosling et al. as one of their original design aims for the language was simplicity and transparency: you should always know what code does simply by looking at it, with no "hidden" effects. ("Simplicity" and Java, oh how the world has changed.)
What you can do is set up a static factory method, something like:

AJSDate startDate = AJSDate.valueOf("200090811");





如果您担心时区,这可能是更好的日期解决方案,因为它允许您将工厂方法重载到同时指定一个时区,你不能轻易地使用运算符重载。



That's probably a better solution for dates if you're concerned about time zones because it allows you to overload the factory method to specify a time zone as well, which you can't easily do with operator overloading.


Java并不像Javascript那样真正工作,尽管Java 10和局部变量类型推断带来的最新变化可能对此有所帮助。在Java 10之前,对象是专门定义的(好吧,即使在Java 10之后)并进行解释,所以当你有


Java does not really work like Javascript, though recent changes brought by Java 10 and local variable type inference may help a bit with this. Before Java 10, objects were specifically defined (ah well, even after Java 10) and interpreted, so when you have

AJSDate startDate = new AJSDate("20090811");





...它告诉JVM您希望使用特定的AJSDate生成类型的对象String对象,注入到提供的构造函数中(我假设你)。



使用Java 10时,如果你有局部变量,你可以有一些这样的东西(局部变量类型推断):



public void someMethod(){

var startDate = new AJSDate(20090811);

}



使用var的Java 10方法非常接近Javascript的行为,但并非完全如此。应用程序的安全性很大程度上依赖于类型安全性。有这样的事情:





... it tells the JVM you want an object of type AJSDate to be generated with that specific String object, injected into the provided constructor (I assume by you).

With Java 10 when you have local variables, you can however have something along the lines of this (local variable type inference):

public void someMethod() {
var startDate = new AJSDate("20090811");
}

The Java 10 method using var gets really close to how Javascript behaves sometimes, but not entirely. Security of an app, relies heavily on type safety. Having something like this:

AJSDate startDate = "20090811";





几乎是错误的,因为你想要等同两种不同的对象类型。



Would pretty much through an error, because you would want to equate two different object types.


这篇关于覆盖赋值运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆