题解 | #类型判断#
类型判断
http://www.nowcoder.com/practice/97223208ca954e67832da716b46e5d72
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
String className = scanner.next();
Base obj = (Base) Class.forName(className).newInstance();
System.out.println(getClassName(obj));
}
}
public static String getClassName(Base obj) {
//write your code here......
if(obj instanceof Sub1)//主要用到关键字instanceof来判断是否属于某个类,把引用类型的判断放在最后
return "Sub1";
else if(obj instanceof Sub2)
return "Sub2";
else
return "Base";
}
}
class Base {
}
class Sub1 extends Base {
}
class Sub2 extends Base {
}