public class Test1 { public static void main(String arg[]) { Object bb=new Test1(); bb.speak(); } void speak() { System.out.print("I am OK!"); } } when I comile the code the following is print out. I think when the speak is invoke ,it only execute the speak of the instance method ,and the instance method speak has been defined,it should not give a copile error. But ........ //---------compile error------------// Test1.java:6: ������������ ���������� speak () �������� in java.lang.Objec bb.speak(); ^ 1 ������ //------------end-----------------// Can you give me a explain about the above.
Valentin Crettaz
Gold Digger
Sheriff
Joined: Aug 26, 2001
Posts: 7610
posted
0
First of all, bb is of type Object and speak() is not defined in Object. You have to cast bb to Test1 in order to get the compilation work ! ------------------ Valentin Crettaz Sun Certified Programmer for Java 2 Platform
I think : the method's calling is according to the type of the instance ,so when invoke the speak,it will call the speak method in class Test1 ,it will not to call the method in Object.
R K Singh
Ranch Hand
Joined: Oct 15, 2001
Posts: 5369
posted
0
Originally posted by Gong James: when I comile the code the following is print out. But ........ //---------compile error------------// Test1.java:6: ������������ ���������� speak () �������� in java.lang.Objec bb.speak(); ^ 1 ������ //------------end-----------------// Can you give me a explain about the above.
Hi Gong when I compile, got this error: //---------compile error------------// D:\JavaTp\Test011114.java:6: Method speak() not found in class java.lang.Object. bb.speak(); ^ 1 error //------------end-----------------//
I think now u must have got what is the error you are getting. and methods are checked by the object reference variable(at compile time). That's why for overriding method should have same signature and return type. at the runtime method is invoked of the object whom that ref variable is pointing. HTH CMIW ------------------ Regards Ravish
[This message has been edited by ravish kumar (edited November 14, 2001).]
"Thanks to Indian media who has over the period of time swiped out intellectual taste from mass Indian population." - Chetan Parekh
Ron Chan
Greenhorn
Joined: Nov 08, 2001
Posts: 11
posted
0
at compile time,the JVM check the oo as a Object Class,but the Class haven't a method called speak,so caused a error,if the Object Class have a speak() method too,then no error and at the runtime the "i am OK"will be output,because at runtime ,oo is regarded as a Test1 Class~