"omerejaz", The Java Ranch has thousands of visitors every week, many with surprisingly similar names. To avoid confusion we have a naming convention, described at http://www.javaranch.com/name.jsp . We require names to have at least two words, separated by a space, and strongly recommend that you use your full real name. Please log in with a new name which meets the requirements. Thanks.
class child cobj= (cobj) new parent (); Omerajaz, Maybe I misunderstand what you are trying to do, but I'm not sure I get what the word "class" is doing here. Also, it seems that you use cobj as an object reference but also as a cast, which doesn't make sense because you normally use class names as casts. My guess is that you need to write: child cobj = (child) new parent(); Hope this helps.
Originally posted by Rosie Vogel: > child cobj = (child) new parent(); This will be illegal as well. You can never downcast an object, only object references. Once created, an object can never change its type. You can refer to it as a different type but only if it is substitutable with the object's actual type. The object created with new parent() is a parent object and can never be thought of as a child object. A child object, however, can be referred to as a parent object.
What you have to understand is that when you instantiate an object, the JVM runs out and gets space on the heap and creates a place to put all of the fields (member variables) for the object. This is all set in stone before the fields get initialized. A subclass is very likely to have MORE fields than it's parent class. If you create an instance of the parent, all the casting in the world is NOT going to make additional fields in the object out on the heap. However if you create a child instance, you can cast it to the parent, because those additional fields will just get ignored.
"JavaRanch, where the deer and the Certified play" - David O'Meara
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
subject: how can a child class be instanciated using it's parent class?