在Java中我们可以写"SuperClassObject instanceof SubClass"吗?

In Java can we write "SuperClassObject instanceof SubClass"?

我可以写这样的代码吗:

 class Shape
{
}
class Circle extends Shape
{
}
public class Main
{
    public static void main(String args[])
    {
        Shape shape = new Circle();
        if (shape instanceof Circle)
        {
            Circle C = (Circle)shape;
        }
    }
}

在上面的代码中我没有提供Shape和Circle中的方法class因为我只是想问一下我是否可以像这样使用instanceof运算符或者没有。

我的意思是这段代码在我的电脑上运行很好,但我怀疑 instanceof 运算符在这种情况下如何正常工作?

I mean this code is running well in my computer...

那个代码不会,它不会编译(因为你试图在没有初始化的情况下使用shape)。

但一般来说,是的,您可以使用 instanceof 来查看对象是否是 class 的实例。这就是它的用途。如果您将 Shape shape; 行更改为

Shape shape = new Circle();

...然后代码将编译,如果你 运行 它,控制将传递到 if 块,因为对象 shape 指的是 Circle.

请注意,检查的是 对象,而不是变量类型。

首先是的,正如我在评论部分提到的那样,您的代码存在编译错误。
回到你的问题是的,你可以使用 instanceof 来查看一个对象是否是特定类型的。 我会推荐你​​关注this.
现在,如果您希望 shape instanceof Circle 为真,则需要像 Shape shape = new Circle();.
一样初始化 shape 否则,如果您初始化 Shape shape = null;,则 shape instanceof Circle 将为假。

API 的 instanceof :

Implementation of the Instanceof operator. Returns a Boolean if the Object parameter (which can be an expression) is an instance of a class type.
Input 1: An object or Expression returning an object.
Input 2: A Class or an Expression returning a Class
Returns: A Boolean that is the result of testing the object against the Class.

检查您提供的对象是否属于您要检查的 class。我认为让您感到困惑的是,归结为 Java 的协方差(您也许可以阅读更多内容)。您可以将变量声明为 SuperClass 类型,并将 SubClass 对象分配给该变量。 就您的示例而言,是这样的:

Shape shape = new Circle();

但是,虽然变量shape被声明为超类类型,但是这个变量里面存储的是一个子类的对象,即Circle。因此,当 instanceof 方法检查变量 shape 的对象以查看它是否是(启动为)Circle 的实例时,它 returns 为真。

这就是 instanceof 非常有用的原因。假设您有另一个子类型:

class Square extends Shape { \*...*\  }

并且你有一些方法,如果它是一个圆,你想做一些特定的事情,如果它是一个正方形,你可以做一些不同的事情,那么你可以有类似下面的东西:

public void doSomethingWithShape(Shape shape) {
    if (shape instanceof Cirlce) {
        // code that handles circles here
    } else if (shape instanceof Square) {
        // code that handles squares here
    }
}

注意:如果它是一个公共方法并且每个子类型都应该有它(简单的例子是 printValues()),那么最好在超级 class 中使用方法(在你的例子中 Shape),然后让每个子类型 class 实现使用该子类型的具体实现细节覆盖该方法 class,然后

Shape shape = new SomeSubTypeOfShape();
shape.printValues(); 

将应用的方法将基于形状中的对象类型 (SomeSubTypeOfShape),并将调用与子类型关联的重写方法。

示例 doSomethingWithShape 只是为了展示如何使用 instanceof - 测试特定对象的 class。即使该变量被声明为分配给该变量的实际 subclass 对象的 superclass,该对象仍然是 subclass.[=19= 的对象]