为什么围绕Java中的类名使用括号? [英] Why are parentheses used around a class name in Java?

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

问题描述

我遇到了一些代码并且无法理解它的某个方面,虽然我做了一些广泛的搜索!

I came across some code and cannot understand a certain aspect of it although i have done some extensive searching!

我的问题是:为什么类有时在括号内声明如下面的代码?

My question is: why are classes sometimes declared within parentheses like in the following code?

public class Animal {

    public static void hide() {
        System.out.println("The hide method in Animal.");
    }

    public void override() {
        System.out.println("The override method in Animal.");
    }
}

public class Cat extends Animal {

    public static void hide() {
        System.out.println("The hide method in Cat.");
    }

    public void override() {
        System.out.println("The override method in Cat.");
    }

    public static void main(String[] args) {
        Cat myCat = new Cat();
        Animal myAnimal = (Animal)myCat;
        myAnimal.hide();
        myAnimal.override();
    }
}

我特别关注这一行代码:

where my focus is on this line of code in particular:

            Animal myAnimal = (Animal)myCat;

我认为这与一个班级扩展另一个班级但不确定班级是什么有关在括号内定义表示。

I believe it has something to do with the fact that one class extends another but am unsure what the class defined within parentheses signifies.

对此有任何帮助表示赞赏。提前谢谢。

Any help on this is appreciated. Thank you in advance.

推荐答案

您所看到的是一个演员,告诉编译器可以将Cat分配给动物。

What you're seeing is a cast to tell the compiler it's ok to assign a Cat to an Animal.

强制转换适用于编译器无法安全地将一种类型转换为另一种类型的情况,因为它不知道所涉及的类型是什么,或者因为转换会丢失信息(例如,如果你有一个想要存储在float类型的变量中的double)。

Casts are for cases where the compiler can't safely convert one type to another, either because it doesn't know what the types involved are, or because the conversion would lose information (for instance, if you have a double that you want to store in a variable of type float).

在你的例子中,演员是完全没必要的,因为Cat扩展了Animal;由于所有Cats都是Animal,编译器不需要显式转换来告诉它可以将Cat分配给Animal。

In your example the cast is totally unnecessary because Cat extends Animal; since all Cats are Animals, the compiler doesn't need an explicit cast to tell it it can assign a Cat to an Animal.

应该为特殊场合保留Casting。如果你经常使用显式的强制转换,那么这可能意味着你没有从类型系统中获得最大的好处。

Casting should be reserved for special occasions. If you use explicit casts regularly then it may mean you're not getting the most benefit out of the type system.

这篇关于为什么围绕Java中的类名使用括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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