有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在Java中,我们可以编写“子类的超类对象实例”吗?

我可以编写如下代码:

 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类中的方法,因为我只是想问一下是否可以像这样使用instanceof操作符

我的意思是,这段代码在我的计算机上运行得很好,但我的疑问是,在这种情况下,instanceof操作符怎么能正常工作


共 (3) 个答案

  1. # 1 楼答案

    首先,是的,正如我在评论部分已经提到的,您的代码中存在编译错误
    回到您的问题“是”,您可以使用instanceof查看对象是否为特定类型。 我将建议您遵循this
    现在,如果希望shape instanceof Circle为真,那么需要初始化类似shapeShape shape = new Circle();
    否则,如果初始化了Shape shape = null;,则shape instanceof Circle将为false

  2. # 2 楼答案

    instanceof的API:

    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.

    如果您提供的对象属于您要检查的类,则会对其进行检查。我认为让你们困惑的是Java的协变性(你们也许可以阅读更多)。可以将变量声明为超类类型,并为该变量指定子类对象。 在您的示例中,类似于以下内容:

    Shape shape = new Circle();
    

    然而,即使变量shape被声明为超类类型,该变量中存储的是子类的对象,即圆。因此,当instanceof方法检查变量shape的对象以查看它是否是(作为Circle启动的)的实例时,它返回true

    这就是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()),那么最好将该方法放在超类中(在Shape中),然后让每个子类型类实现使用该子类的特定实现细节覆盖该方法,然后

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

    将应用的方法将基于shape中的对象类型(SomeSubjectOfShape),并将调用与该子类型关联的重写方法

    示例doSomethingWithShape只是为了说明如何使用instanceof来测试特定对象的类。即使变量被声明为分配给变量的实际子类对象的超类,该对象仍然是子类的对象

  3. # 3 楼答案

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

    如果代码不会,它就不会编译(因为您试图在不初始化它的情况下使用shape

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

    Shape shape = new Circle();
    

    。。。。然后代码将编译,如果您运行它,控件将传递到if块,因为shape引用的对象是Circle

    请注意,选中的是对象,而不是变量类型