六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 23|回复: 0

我的理解 instanceof 用法

[复制链接]

升级  40%

4

主题

4

主题

4

主题

童生

Rank: 1

积分
20
 楼主| 发表于 2013-2-4 20:23:14 | 显示全部楼层 |阅读模式
intanceof()方法主要用来判断变量的类型。
使用Object类型在构造器中,间接达到了多态的效果。
import java.lang.reflect.*;class ClassA{private int a;private String b;private int[] c;ClassA(Object temp){if(temp instanceof Integer){//判断输入的是整型a = Integer.parseInt(temp.toString());System.out.println("this is an <"+ temp.getClass().getName() +"> type. Integer value=" + a);}else if(temp instanceof String){//判断输入的是字符串b = temp.toString();System.out.println("this is a <"+ temp.getClass().getName() +"> type. String value=" + b);}else if(temp instanceof int[]){//判断输入的是整型数组int n = Array.getLength(temp);int[] c = new int[n];for(int i = 0;i < n; i++){c[i] = Array.getInt(temp,i);}System.out.print("this is an <"+ temp.getClass().getName() +"> type. Int[]array value=");for(int i = 0;i < n; i++){System.out.print(c[i] + ", ");}System.out.println();}}public static void main(String[] args){ClassA test1= new ClassA(12);ClassA test2= new ClassA("OK");int tmp[] = {1,2};ClassA test3= new ClassA(tmp);}}
我是初学者,还希望大家指教。
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表