博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java中的类型转换
阅读量:2532 次
发布时间:2019-05-11

本文共 4557 字,大约阅读时间需要 15 分钟。

In this tutorial, we’ll be discussing typecasting and its various forms in Java. Let’s get started.

在本教程中,我们将讨论Java中的类型转换及其各种形式。 让我们开始吧。

Java中的类型转换 (Type Casting in Java)

In simple terms, type casting means converting the type of a primitive/reference variable. We’ll be dealing with three types of scenarios in typecasting:

简而言之,类型转换意味着转换基本类型/引用变量的类型。 我们将在类型转换中处理三种类型的场景:

  • Primitive types

    原始类型
  • Object types

    对象类型
  • Wrapper Classes and primitives

    包装器类和基元

Hence, this tutorial would be divided into three parts:

因此,本教程将分为三个部分:

  • Widening and Narrowing

    加宽和缩小
  • Upcasting and Downcasting

    上流和下流
  • Autoboxing and Unboxing

    自动装箱和拆箱

Just for the sake of simplicity and in order to differentiate the primitive and reference type examples we are using different terms.

为了简单起见,为了区分原始类型和引用类型的示例,我们使用了不同的术语。

Let’s get started!

让我们开始吧!

1.宽窄型铸造 (1. Widening and Narrowing Type casting)

Widening means a small type can be accommodated in a larger type without any loss of information.

加宽意味着可以将小型字体容纳在大型字体中,而不会丢失任何信息。

Widening Typecasting is automatic.

加宽类型转换是自动的。

That means a byte value can be automatically casted to short, int, long or double.

这意味着可以将字节值自动转换为short,int,long或double。

Widens from left to right.

从左到右加宽。

boolean types cannot be cast to anything else. They are always true or false.

布尔类型不能强制转换为其他任何类型。 它们始终是对还是错。

Example:

例:

Jshell Wide Type Casting

Jshell Wide Type Casting

Jshell宽型铸件

Let’s look at another example:

让我们看另一个例子:

Jshell Type Casting Error

Jshell Type Casting Error

Jshell类型转换错误

As you can see, wide to narrow typecasting automatically would lead to a compile-time error.

如您所见,宽到窄类型转换会自动导致编译时错误。

For that, we need to do explicit type casting as:

为此,我们需要将显式类型强制转换为:

Jshell Narrow Type Casting

Jshell Narrow Type Casting

Jshell窄型铸造

This is narrow typecasting and must be done manually.

这是狭窄的类型转换,必须手动完成。

2.上下行 (2. Upcasting and Downcasting)

In simple words :

Upcasting is casting from a subclass to a superclass.
Downcasting is casting from a superclass to a subclass.

简单来说:

向上转换从子类转换为超类。
向下转换是从超类转换为子类。

Upcasting happens automatically and we do not have to do anything explicitly.

Downcasting if done implicitly can cause a compiler error.

向上转换是自动发生的,我们不必明确地做任何事情。

如果隐式完成向下转换,则可能导致编译器错误。

In the following examples, our inheritance tree would like :

在以下示例中,我们的继承树将如下所示:

JournalDev -> Java -> Android

JournalDev-> Java-> Android

// Base Classclass JD{    public void printMe() { System.out.println("JournalDev print method"); }}// Inherited classclass Java extends JD{    public void printMe() { System.out.println("Java print method"); }}// Inherited classclass Android extends Java{    public void printMe() { System.out.println("Android print method"); }} class Main{    public static void main(String[] args)    {        JD jd = new Java();        jd.printMe(); //prints Java print method    }}

The above case is an example of upcasting.

上面的例子是一个向上转换的例子。

Let’s use the same concept on downcasting and see what happens:

让我们在向下转换中使用相同的概念,看看会发生什么:

Android android = new Java();

This will cause a compile-time error.

Use the following instead:

这将导致编译时错误。

请改用以下内容:

Java java = new Android();Android and = (Android) java;
ClassCastException is thrown.
抛出ClassCastException

Let’s say we have a class like:

假设我们有一个类似的类:

class JavaEE extends Java{    public void printMe() { System.out.println("JavaEE print method"); }}

Now:

现在:

Java java = new Android();JavaEE javaEE = (JavaEE)java; //classcastexception

To tackle such cases, use instanceof operator before typecasting.

要解决这种情况,请在类型转换之前使用instanceof运算符。

Downcasting is typically used when we want to access specific behaviors of subtype.

当我们要访问子类型的特定行为时,通常使用向下转换。

3.自动装箱和拆箱 (3. AutoBoxing and unboxing)

If we want to use primitive types as reference objects, we can use their equivalent wrapper classes.

如果我们想使用原始类型作为引用对象,则可以使用它们的等效包装器类。

Example: int has Integer and so on…

例如:int具有Integer等等。

Autoboxing refers to automatically converting a primitive type to a reference type.

自动装箱是指将原始类型自动转换为引用类型。

Example:

例:

ArrayList&ltInteger> arrayList = new ArrayList<>();arrayList.add(1);

Here we added a primitive type to a reference type by automatically boxing it.

在这里,我们通过自动装箱将原始类型添​​加到引用类型。

Unboxing means converting an object of a wrapper type to its corresponding primitive value For example conversion of Integer to int

拆箱意味着将包装类型的对象转换为其对应的原始值,例如,将Integer转换为int

To explicitly unbox we can use the built-in methods such as intValue(), floatValue() and so on:

要显式地取消装箱,我们可以使用诸如intValue(),floatValue()等内置方法:

Integer obj = new Integer("123");      int i = obj.intValue();      System.out.println(i); //123

That brings an end to this tutorial on Type casting in Java.

这结束了有关Java中的类型转换的本教程。

翻译自:

转载地址:http://rjlzd.baihongyu.com/

你可能感兴趣的文章
pg 生成数据字典
查看>>
ecshop底部版权修改和组成分析
查看>>
实验六
查看>>
Facebook IV Winner's Interview: 1st place, Peter Best (aka fakeplastictrees)
查看>>
葛剑雄:读书方法决定你的命运
查看>>
java安装包地址
查看>>
ASP.NET MVC和EF集成AngularJS开发
查看>>
游苹果山赋——东南子(2010年旧文)
查看>>
团队项目---测试与调试
查看>>
BZOJ 1699 [Usaco2007 Jan]Balanced Lineup排队
查看>>
关于uitableviewcell的accessoryType属性
查看>>
Spring Boot启动过程及回调接口汇总
查看>>
按位计数法
查看>>
17:网络编程
查看>>
Redis缓存方案
查看>>
LwIP buffer management, memory configuration options
查看>>
JMeter 聚合报告之 90% Line 参数说明
查看>>
Python环境——安装扩展库
查看>>
HTML常用标签
查看>>
Python MySQLdb 学习总结(转)
查看>>