• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

ChildClass childClass=new ParentClass()

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?

 
Sheriff
Posts: 14691
16
Eclipse IDE VI Editor Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 VI Editor Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
And welcome to the ranch
You may be interested to read this tutorial about inheritance.
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Chris and Fred..

How is the JVM is letting me do this

Child c =(Child) new Parent();
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic