|
该帖已经被评为新手帖
|
|
|---|---|
| 作者 | 正文 |
|
最后更新时间:2007-10-09 关键字: instanceof Object
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);
}
}
我是初学者,还希望大家指教。 声明:JavaEye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
|
|
| 返回顶楼 | |
|
最后更新时间:2007-10-10
直接使用多态不好吗?不要用instanceof这种方式,程序会变得难以维护。
|
|
| 返回顶楼 | |
|
最后更新时间:2007-10-10
这种程序写的很烂!!
|
|
| 返回顶楼 | |
|
最后更新时间:2007-10-10
直接用多态好一点.让编译器去找合适的永远比你自己写来的方便
|
|
| 返回顶楼 | |
|
最后更新时间:2007-10-10
看到了大家中肯的评价。
这里只是说明了instanceof的用法,不是说就打算这么写代码了。最近在学习很基本的数据结构,用Object来建立栈、队什么的,用instanceof来判断类型挺好的。 |
|
| 返回顶楼 | |
|
最后更新时间:2007-10-10
这个玩样用重载就可以了
这样用instanceof 是要死人地!而且一点也不OO. |
|
| 返回顶楼 | |
|
最后更新时间:2007-10-10
instanceof我一般用在接口上,判断是哪种接口再去做
|
|
| 返回顶楼 | |
|
最后更新时间:2007-10-10
惊鸿逝水 写道 这种程序写的很烂!!
你看到的是这个? |
|
| 返回顶楼 | |
|
最后更新时间:2007-10-10
phoenixup 写道 惊鸿逝水 写道 这种程序写的很烂!!
你看到的是这个? 方向不对,努力白费!这种做法有什么好鼓励?且不说是不是所谓的多态,请你认真看看他程序实现了什么? 滥用、乱用instanceof去实现简简单单的setter方法!很值得鼓励吗?我鼓励他会觉得我很虚伪,还是你来吧! |
|
| 返回顶楼 | |
|
最后更新时间:2007-11-01
我觉得就不错,
学习是没有对错的! |
|
| 返回顶楼 | |







