方法实例究竟是如何工作的?以及为什么它在下面显示的代码中不起作用



所以我定义了下面显示的主类,我定义了一个单词类和一个句子类。 请注意,程序在运行时应返回 false。但是,当我运行它时,我收到"不兼容的条件操作数类型单词和句子"错误。这不是使用运算符实例的方式还是我感到困惑?如何修改我的程序以运行而不会崩溃?

public class main{
public static void main (String[] args){
    words example = new words("heyo");
    sentence ex = new sentence("wats up dog");
    System.out.println(example instanceof sentence);
}
}

如果您运行instanceof的变量不能与您提供给运算符的类属于同一类型,则代码将不会编译。

由于examplewords类型,它不是sentence的子类或超类,instanceof不能应用于examplesentence

以下是 JLS 15.20.2 对表达式"RelationalExpression instanceofReferenceType"的描述:

如果将关系表达式强制转换为 ReferenceType 将作为编译时错误被拒绝,则关系表达式实例同样会产生编译时错误。在这种情况下,表达式实例的结果永远不可能是真的。

在运行时,如果 RelationalExpression 的值不为 null,并且引用可以强制转换为 (§15.16( 到 ReferenceType 而不引发 ClassCastException,则 instanceof 运算符的结果为 true。否则结果为假。

你的类,即句子应该与你的示例来自(即单词的类型或子类型(处于相同的层次结构中,以便编译。以下是相同的示例,这是它所说的实例:

The instanceof operator compares an object to a specified type. You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.

如果单词不是句子类的子类,则示例对象不可能是句子的实例。

方法的实例仅适用于同一层次结构中的类。例如:-

Class A{
}
Class B extends A {
}
Class C{
}
// in your main 
A a = new B();
// then you can check if a is object of B
System.out.println(a instanceOf B);
//You cannot do 
System.out.println(a instance of C);
// as no way you cannot do this
  A a = new C();

instanceof运算符中,如果 LHS(实例(不是 RHS(类(的实例,则返回 false,反之亦然。但是,在您的情况下,编译器很容易解决这些是不兼容的类型,因此它会抱怨。

所以像下面这样(类似于你的例子(:

String a = "asd";
Integer b = new Integer(12);
System.out.println(""+ (b instanceof String)); // compile time error

永远不会编译。但是,如果编译器无法确定如下情况,则当您运行时它将返回false

public static void main(String[] args) {
  String a = "asd";
  Integer b = new Integer(12);
  check (b); // prints false
}
public static void check(Object o) {
  System.out.println(o instanceof String);
}

最新更新