Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Polymorphic method inside Constructor  RSS feed

 
priyankjecrc jain
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why in this code testSon class void display() method is called instead of testFather class void display()










Output : This is testSon class /* why not This is testFather class*/
This is cons of testSon class
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I know a lot of people are taught to write parent and child, but that gives you a misleading impression of object‑oriented inheritance; it is different from biological inheritance so you are better writing Super and Sub. Or even better consider real names like Animal→Cat and Animal→Dog.
I added code tags to your post. Always use them: doesn't it look better

Now, to your actual question.
Instance methods are polymorphic, so the compiler does not decide which method to call. It is called by the JVM at runtime, according to the runtime type of the object. If you have a method in Cat, that is called from the Cat constructor whether you declare the reference as Cat or Animal. So your subclass' object is called. Same as if you wrote this:-The cat will mew; it will not roar or bark. Similarly if you called the makeNoise method from a Cat constructor you will get a mew not a roar or bark. This is standard polymorphic behaviour. And you often don't want it. So we have a design principle to endure the constructor behaves as you expect:-
If you call a method from a constructor, it should be marked private or final.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!