关于在Java中调用子类方法

时间:2015-09-04 08:16:07

标签: java

以下代码来自教科书:

CommissionEmployee3 commissionEmployee = new CommissionEmployee3(
"Sue", "Jones", "222-22-2222", 10000, .06 );

BasePlusCommissionEmployee4 basePlusCommissionEmployee =
new BasePlusCommissionEmployee4(
"Bob", "Lewis", "333-33-3333", 5000, .04, 300 );

System.out.printf( "%s %s:\n\n%s\n\n",
"Call CommissionEmployee3's toString with superclass reference ",
"to superclass object", commissionEmployee.toString() );

System.out.printf( "%s %s:\n\n%s\n\n",
"Call BasePlusCommissionEmployee4's toString with subclass",
"reference to subclass object",
basePlusCommissionEmployee.toString() );

CommissionEmployee3 commissionEmployee2 =
basePlusCommissionEmployee;

System.out.printf( "%s %s:\n\n%s\n",
"Call BasePlusCommissionEmployee4's toString with superclass",
"reference to subclass object", commissionEmployee2.toString() );

我想问为什么它可以使用" commissionEmployee2.toString()"?

编译器是否会出错?

2 个答案:

答案 0 :(得分:2)

如果类没有该方法,则会发生编译器错误。但是 <flow name="testsFlow"> <http:listener config-ref="HTTP_Listener_Configuration" path="/" doc:name="HTTP"/> <scripting:component doc:name="Groovy"> <scripting:script engine="Groovy"><![CDATA[return tests.OrdersStreamIterator.class.getClassLoader().getResourceAsStream("orders.xml");]]></scripting:script> </scripting:component> <set-payload value="#[new tests.OrdersStreamIterator(payload)]" doc:name="Iterator"/> <foreach doc:name="For Each"> <logger message="#[tests.OrdersStreamIterator.dump(payload)]" level="INFO" doc:name="Logger"/> </foreach> </flow> 使用了超类方法哪个Object类。

toString()方法属于Object类,它是所有Java类的超类,因此没有错误。

如果在类中重写它,它会执行该过度实现,否则执行Object类的默认实现。

答案 1 :(得分:1)

toString()方法在Object类中定义,它是所有Java类的超类。您可以在类中覆盖您的要求,否则默认实现由Object类提供。

如何使用toString()