This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
hi! I was trying to instanciate the child class object which inherit the properties of the parent class and an error of incompatible type is shown , i did it like this
class child cobj= (cobj) new parent (); i explicitely type cast the object but still there the problem i am compiling this program under jdk 1.3 , if there's any way out?
"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 agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.
subject: how can a child class be instanciated using it's parent class?