为什么Java中有Primitive数据类型? [英] why are there Primitive datatype in Java?

查看:206
本文介绍了为什么Java中有Primitive数据类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

当我们有包装类时,为什么支持原语?

如果有Wrapper类使Java纯面向对象语言,那么为什么有可以在Java中使用的Primitive数据类型???

If there are Wrapper classes which make Java pure object-oriented language, then why are there Primitive datatypes which can be used in Java???

推荐答案

为了提高效率。原始类型的变量直接包含值;非原始类型的变量是引用,引用存储在内存中其他位置的对象。

For efficiency. Variables of primitive types contain the value directly; variables of non-primitive types are references, referring to an object stored somewhere else in memory.

每次需要使用包装类型的值时,JVM需要查找内存中的对象以获取值。原始类型不需要这样,因为变量包含值本身,而不是对包含该值的对象的引用。

Each time you need to use the value of a wrapper type, the JVM needs to lookup the object in memory to get at the value. This isn't needed for primitive types, because the variable contains the value itself, instead of a reference to an object that contains the value.

但是,这不是解释为什么原始类型需要在Java编程语言中明确可见。 Java语言和JVM的设计者可以选择隐藏语言本身的原始类型,以便您可以将所有内容视为对象;然后编译器可以将它翻译成更有效的原始类型。

However, that doesn't explain why primitive types need to be explicitly visible in the Java programming language. The designers of the Java language and the JVM could have chosen to hide primitive types from the language itself, so that you could treat everything as an object; the compiler could then translate it under the covers to more efficient primitive types.

在JVM上运行的一些较新的编程语言(Groovy,Scala和其他)可以让你完全那:在语言本身,一切看起来都像一个对象,你可以在其上调用方法,但在封面下,编译器会将它们转换为基元。

Some newer programming languages that run on the JVM (Groovy, Scala and others) let you do exactly that: in the language itself everything looks like an object, which you can for example call methods on, but below the covers the compiler translates them to primitives.

我想这是在Java语言开发的时候(1990年代上半期),人们没有想到这一点,现在为了允许这种语言的彻底改变为时已晚。

I guess that in the time the Java language was developed (in the first half of the 1990's) people didn't think of that, and now it's too late for a radical change in the language to allow this.

这篇关于为什么Java中有Primitive数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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