aspose file tools*
The moose likes Beginning Java and the fly likes polymorphism Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "polymorphism" Watch "polymorphism" New topic
Author

polymorphism

cchetan jain
Ranch Hand

Joined: Jul 05, 2009
Posts: 30
class A
{
int x=5;
}

class B extends A
{
int x=6;
}



class covtest
{

public A getObject()
{
System.out.println("its A from covtest");
return new A();
}


public static void main(String arg[])
{
covtest t = new subcovtest();
System.out.println(t.getObject().x); // *
}
}



class subcovtest extends covtest
{
public B getObject()
{
System.out.println("its B from subcovtest");
return new B();
}
}
the output is:
its B from subcovtest
5;
expected output is:
its B from subcovtest
6;
please explain,why?
Frank Kellinghusen
Greenhorn

Joined: Jul 10, 2009
Posts: 11
Your code us unreadable:

http://faq.javaranch.com/java/UseCodeTags
cchetan jain
Ranch Hand

Joined: Jul 05, 2009
Posts: 30
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39877
    
  28
Frank Kellinghusen wrote:Your code us unreadable:

http://faq.javaranch.com/java/UseCodeTags
It's not much better without indentation.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39877
    
  28
Frank Kellinghusen, welcome to JavaRanch

Cchetan Jain, remember that polymorphism doesn't apply to fields, nor to static members.
shivendra tripathi
Ranch Hand

Joined: Aug 26, 2008
Posts: 263
t.getObject() will be decided at run time while t.getObject().x will be decided at compile time. Because polymorphism is appicable only for instance mehtod.


SCJP 1.5(97%) My Blog
cchetan jain
Ranch Hand

Joined: Jul 05, 2009
Posts: 30
hello shivendra tripathi..please explain what is the concept behind the t.getObject().x;
when t.getObject() returns B then simply it must return 6..i m confused with this..
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19762
    
  20

I repeat:
Campbell Ritchie wrote:remember that polymorphism doesn't apply to fields, nor to static members.


When accessing fields or static methods, the JVM uses the reference type. Since t's reference type is covtest, it's getObject() method return type is A, not B*. Therefore, A's field x is used.

* The actual type (as returned by getClass()) is B, but the declared type is A.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39877
    
  28
Rob Prime wrote:* The actual type (as returned by getClass()) is B, but the declared type is A.
I thought it would be something like that.

Rob is very good about that sort of thing. Thank you, Rob
cchetan jain
Ranch Hand

Joined: Jul 05, 2009
Posts: 30
thanks for your wisdom...
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39877
    
  28
You're welcome
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: polymorphism