【发布时间】:2017-02-25 18:36:41
【问题描述】:
我有父类和子类,其中父类有一个方法-getData。无论是否创建对象,我都可以直接从子类调用此方法。
我想知道该方法如何在不创建对象的情况下在子类中可用。 (它也不是静态方法)
我的理解是我们必须创建一个对象来访问这些方法。谁能解释一下为什么?
public class testbase {
public void getData(String Data) throws IOException{
Properties prop1;
prop1= new Properties();
FileInputStream f= new FileInputStream("C:\\file.properties");
prop1.load(f);
String data= prop1.getProperty(Data);
System.out.println(data);
}
}
class testproperties_file extends testbase {
@Test
public void test_class() throws IOException{
getData("name");
}
}
【问题讨论】:
-
什么意思“不创建对象”?你创建了一个
testproperties_file的实例,不是吗? -
子实例是父实例。这就是继承的全部意义。如果动物会跑,那我可以让狗跑,因为狗是动物。
-
当执行在子类中时,调用在
this。它指的是当前对象。而当你调用test_class方法时,会在testproperties_file的对象上调用。
标签: java inheritance