wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes ChildClass childClass=new ParentClass() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ChildClass childClass=new ParentClass() " Watch "ChildClass childClass=new ParentClass() " New topic
Author

ChildClass childClass=new ParentClass()

Raj Srimandal
Greenhorn

Joined: Mar 13, 2008
Posts: 10
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

Joined: Nov 24, 2005
Posts: 14687
    
  16

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 :


[My Blog]
All roads lead to JavaRanch
Christophe Verré
Sheriff

Joined: Nov 24, 2005
Posts: 14687
    
  16

And welcome to the ranch
You may be interested to read this tutorial about inheritance.
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11153
    
  16




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.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Raj Srimandal
Greenhorn

Joined: Mar 13, 2008
Posts: 10
Thanks Chris and Fred..

How is the JVM is letting me do this

Child c =(Child) new Parent();
 
Consider Paul's rocket mass heater.
 
subject: ChildClass childClass=new ParentClass()
 
Similar Threads
Can we extend multiple classes ?
Polymorphism applies to instance methods not instance variables?
Protected Scope
Question on Extensibility