2020.8.24收获
学习内容:
instanceof关键字
作用:判断一个对象是否属于一个类
格式:对象 instanceof 类 ——返回布尔类型
1 package com.study; 2 class Animal{ 3 public void say() { 4 System.out.println("我是一只动物"); 5 } 6 } 7 class Dog extends Animal{ 8 public void say() { 9 System.out.println("我是一只狗"); 10 } 11 public void f1() { 12 System.out.println("我是人类的朋友!"); 13 } 14 } 15 class Cat extends Animal{ 16 public void say() { 17 System.out.println("我是一只猫"); 18 } 19 public void f2() { 20 System.out.println("我喜欢吃鱼!"); 21 } 22 } 23 24 public class Test { 25 public static void something(Animal animal) { 26 animal.say(); 27 if(animal instanceof Dog) { 28 ((Dog) animal).f1(); 29 } 30 if(animal instanceof Cat) { 31 ((Cat) animal).f2(); 32 } 33 } 34 public static void main(String[] args) { 35 Animal animal=new Dog(); 36 System.out.println("animal对象是否属于Animal类:"+(animal instanceof Animal)); 37 System.out.println("animal对象是否属于Dog类:"+(animal instanceof Dog)); 38 System.out.println("animal对象是否属于Cat类:"+(animal instanceof Cat)); 39 40 something(new Dog()); 41 something(new Cat()); 42 } 43 }