This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ChildClass childClass=new ParentClass()

 
Raj Srimandal
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a concrete Parent class(ParentClass) and Child Class(ChildClass) which inherits from ParentClass.I cannot say

ChildClass childClass=new ParentClass() ..i.e this is a compile time check
Does anyone know WHY?

 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does anyone know WHY?

Does anybody doesn't ? You have a "public class ChildClass extends ParentClass". ChildClass may have some methods that ParentClass doesn't. How could you instantiate the parent and assign it to a child ? You probably want to do the opposite :
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the ranch
You may be interested to read this tutorial about inheritance.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12087
29
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator



if you wrote this:



What would happen when you then called


The object that is actually created has NO IDEA what methodB() is - it doesn't exist. But the reference says that you can call it.

It would be like saying you have a "class Animal" and a ''class fish extends animal". You can refer to any fish as an animal, but you can't refer to any animal as a fish.

 
Raj Srimandal
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Chris and Fred..

How is the JVM is letting me do this

Child c =(Child) new Parent();
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic