instanceof 的语法格式如下:
myobject instanceof ExampleClass
myobject:某类的对象引用
ExampleClass:某个类
1 class Quadrangle{ 2 public static void draw(Quadrangle q) { 3 } 4 } 5 6 class Square extends Quadrangle { 7 8 } 9 10 class Anything { 11 12 } 13 public class Parallelogram extends Quadrangle { 14 15 public static void main(String[] args) { 16 17 Quadrangle q = new Quadrangle(); 18 //判断父类对象是否为Parallelogram子类的一个实例 19 if(q instanceof Parallelogram) { 20 Parallelogram p = (Parallelogram) q; 21 } 22 if(q instanceof Square){ 23 Square s = (Square)q; 24 } 25 } 26 27 }
时间: 2024-10-06 18:53:29