Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General 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: 12122
30
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