0

the code below is from the textbook :

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() );

I want to ask why it can use "commissionEmployee2.toString()"?

Does't the compiler get errors?

  • `toString()` is a method that is inherited by every Java objects (it is defined in `Object`, the superclass of all classes) – Tunaki Sep 04 '15 at 08:17

2 Answers2

2

Compiler error occurs if the class doesn't have that method. But the commissionEmployee2 using super classes method which Object class.

toString() method belongs to Object class which is super class of all Java classes, hence the no error.

If you override it in your class, it executes that over-ridden implementation otherwise the default implementation from Object class.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • Could I also ask why the textbook says commissionEmployee2.toString() actually calls subclass BasePlusCommissionEmployee4's toString method? –  Sep 04 '15 at 09:14
  • Does what commissionEmployee2.toString() really calls is its class method, not subclass method, and I have to downcast superclass variable from superclass type to subclass type in order to call subclass method? –  Sep 04 '15 at 09:58
1

toString() method is defined in Object class which is super class of all Java classes. you can override in your class for your requirement otherwise default implementation is provided by Object class.

How to use toString()

Community
  • 1
  • 1
Rustam
  • 6,485
  • 1
  • 25
  • 25
  • Does what commissionEmployee2.toString() really calls is its class method, not subclass method, and I have to downcast superclass variable from superclass type to subclass type in order to call subclass method? –  Sep 04 '15 at 11:34