Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

polymorphism ??

 
Ram Murthy
Ranch Hand
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 340
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Gokul Somasundaram
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Program returns 5 for me in Java 1.4.2
 
A Kumar
Ranch Hand
Posts: 980
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 91
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the response.
Sandy -- 10 was typo it should have been 20.

Now I understand why it prints 5.

Cheers,
JP
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic