Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 了解它所指向的继承类_Java_Inheritance - Fatal编程技术网

Java 了解它所指向的继承类

Java 了解它所指向的继承类,java,inheritance,Java,Inheritance,我有一个基类base和一对继承的基类base_1、base_2、base_3。我有一个基于代码的测试,但如何发现它所指向的类:BASE_1、BASE_2或BASE_3 我不清楚你在问什么,但你可以使用getClass()方法和instanceof操作符 如果是这样的话 Base b = new Child1(); b.getClass();//will give you child1 要查看特定对象的类名,可以使用: test.getClass().getName(); 但是您通常不应该在意

我有一个基类base和一对继承的基类base_1、base_2、base_3。我有一个基于代码的测试,但如何发现它所指向的类:BASE_1、BASE_2或BASE_3

我不清楚你在问什么,但你可以使用
getClass()
方法和
instanceof
操作符

如果是这样的话

Base b = new Child1();
b.getClass();//will give you child1

要查看特定对象的类名,可以使用:

test.getClass().getName();

但是您通常不应该在意,因为任何依赖于您拥有的子类的功能都应该作为这些子类中的重写(“多态”)函数来实现。

您可以使用
instanceof
检查特定类型或
.getClass()
获取描述特定类的
对象:

Base test = getSomeBaseObject();

System.out.println("test is a " + test.getClass().getName());
if (test instanceof Base1) {
  System.out.println("test is a Base1");
}
BASE test = getSomeBase();

// method 1
System.out.println(test.getClass().getName());  // prints the classname

// method 2
if (test instanceof BASE_1) {
   // test is a an instance of BASE_1
}