About InstanceOf operator

xiaoxiao2021-03-06  52

EXAMPLE: Class Teacher and Student Are Subclass of Class Person.

Person P;

Teacher T;

STUDENT S;

P, T And S Are All Non-Null.

IF (T) {s = (student) t;}

What is the result of this society?

A. IT Will Construct A Studient Object.

B. The Expression is Legal.

C. IT IS ILLEGAL AT Compilation.

D. IT IS LEGAL At Compilation But Possible Illegal At Runtime.

(c) The role of the instanceOf operator is to determine if a variable is an object of the class pointed out by the right operand. Since the polymorphism of the Java language makes it possible to assign an instance of a sub-class to one

The parent class variables, and in some cases, it is necessary to determine the variable in the end, and INSTANCEOF can be used at this time. When the left operation is the act of the class pointed out

Alternatively, the instance of the subclass is returned. If it is assigned to the instance of a sub-class to a parent class, it will also return to whether the variable is an instance of the subclass with instance.

Return. The judgment of the IF statement in this question is no problem, and it will return true, but the later type conversion is illegal, because T is a Teacher object, it cannot be forced to convert to a

The Student object, even the two classes have a common parent class. If it is converted to a Person object, it is not necessary to force conversion. This error can be found when compiling.

Therefore, compilation cannot pass.

转载请注明原文地址:https://www.9cbs.com/read-110360.html

New Post(0)