简体   繁体   English

Java 被强类型化

[英]Java being strongly typed

I came across this section in some class notes:我在一些 class 笔记中遇到了这一部分:

在此处输入图像描述

Java programs are what is known as statically and strongly typed. Java 程序是所谓的静态和强类型。

I'm familiar with the concept of static or dynamic types, but haven't come across strong/weak types, and in looking them up there is always some wishy-washy definition.我熟悉 static 或动态类型的概念,但没有遇到强/弱类型,并且在查找它们时总是有一些空洞的定义。

In the above, what would be an example of how Java is strongly typed?在上面,Java 是如何强类型化的示例是什么? Does it just mean that you cannot cast one type to another (but what about casting an int to a long or something of the same conceptual type)?这是否只是意味着您不能将一种类型转换为另一种类型(但是将int转换为long或相同概念类型的东西呢)? How does the concept of strong/weak types relate to Java?强/弱类型的概念与 Java 有什么关系?

In a Weakly Typed language conversion between unrelated data types is implicit.弱类型语言中,无关数据类型之间的转换是隐式的。

For eg JavaScript is a Weakly Typed language:例如 JavaScript 是弱类型语言:

var x = 22;
var y = x + "example";
console.log(y);  # prints 22example as an instance of String object
# Here the value of x got converted to string without any explicit conversion by the programmer.

A Strongly Typed language is exact opposite.强类型语言正好相反。 You can do type conversion in Strongly Typed languages, but they are not implicit.您可以在强类型语言中进行类型转换,但它们不是隐式的。 You have to do them explicitly.您必须明确地执行它们。

For eg Java is a Strongly Typed language:例如 Java 是一种强类型语言:

int x = 2;
Long y = x; # Will throw compilation error
# However you can do something like below example
Long y = new Long(x);
# There are other ways to do type conversion in java for different data types, but they are not implicit, you gotta do them explicitly.

I hope this answers your question.我希望这回答了你的问题。

Strongly typed means, variable's data type has to be defined in program.强类型意味着,变量的数据类型必须在程序中定义。 This data type will be fixed at compile time.此数据类型将在编译时固定。 Unlike in loosely typed, where don't declare data type for variable in program.与松散类型不同,在程序中不为变量声明数据类型。 Data types are assigned in these cases at runtime.在这些情况下,数据类型是在运行时分配的。

Javascript is a loosely and dynamically typed language. Javascript 是一种松散的动态类型语言。 Here we declare like: var age="old";在这里我们声明如下: var age="old"; var income= 4000000; var 收入 = 4000000; Here, age will be made string type and income will numbers type at runtime in JS.在这里,年龄将被设为字符串类型,收入将在 JS 运行时设为数字类型。

Hope this contrast between Java and JavaScript helps in understanding this concept.希望 Java 和 JavaScript 之间的对比有助于理解这个概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM