File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes polymorphism ?? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "polymorphism ??" Watch "polymorphism ??" New topic
Author

polymorphism ??

Ram Murthy
Ranch Hand

Joined: Aug 02, 2005
Posts: 91
public class Child extends Parent
{
public static int test(int i)
{
return 20;
}
public static void main(String[] args)
{
Parent c = new Child();
System.out.println(c.test(10));
}
}
class Parent
{
public static int test(int i)
{
return 5;
}
}

the above code compiles and runs fine. It gives output of 5. Althoug I thought it will return 10.
Even though c is of type Parent it is pointing to Child object so during execution time wouldn't it call the test method in Child and return 10.

Please clarify ...thanks

Cheers,
JP


Cheers,
Ram
A Kumar
Ranch Hand

Joined: Jul 04, 2004
Posts: 979
HI,

The methods are static method ..they cannot be overridden..


Whne you are calling static methods ..they depend upon the type rather than

the object...Which is unlike the instance methods...

Also go through the below link..

http://www.coderanch.com/t/251030/java-programmer-SCJP/certification/Static-declaration

Sandeep Chhabra
Ranch Hand

Joined: Aug 28, 2005
Posts: 340
Originally posted by JP Ravi:
the above code compiles and runs fine. It gives output of 5. Althoug I thought it will return 10.
Even though c is of type Parent it is pointing to Child object so during execution time wouldn't it call the test method in Child and return 10.

Please clarify ...thanks

Cheers,
JP


Hi,
I dont think it will ever return 10, Whichever method may the statement call.
you have just two return statements in your code :
return 20; in Child Class
return 5; in Parent Class


Regards<br />Sandy<br />[SCJP 5.0 - 75%]<br />[SCWCD 1.4 - 85%]<br />------------------<br />Tiger, Tiger burning bright,<br />Like a geek who works all night,<br />What new-fangled bit or byte,<br />Could ease the hacker's weary plight?
Gokul Somasundaram
Greenhorn

Joined: Jul 17, 2005
Posts: 20
The Program returns 5 for me in Java 1.4.2
A Kumar
Ranch Hand

Joined: Jul 04, 2004
Posts: 979
Hi Gokul,

You are right about the result...

And why you get it....as 5 ...has been mentioned in the above posts..

Ram Murthy
Ranch Hand

Joined: Aug 02, 2005
Posts: 91
Thanks for the response.
Sandy -- 10 was typo it should have been 20.

Now I understand why it prints 5.

Cheers,
JP
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: polymorphism ??