Casting parent class to a child class

I have a static method which returns a class called parent. Now I want to cast it it's child class. There are no compilation errors, but at runtime it's throwing me ClassCastException. This is what I'm doing.
public Parent getObject() {
Parent p = new Parent();
return p;
Child c = (Child) getObject();What is wrong with this code? I couldn't figure it out.
Any help will be appreciated.

Parent p1 = new Parent(); // 1
Parent p2 = new Child(); // 2
Child c1 = new Parent(); // 3
Child c2 = new Child(); // 4
Parent p1 = (Parent)c1; // 5
Parnet p2 = (Parent)c2; // 6
Child c3 = (Child)p1; // 7
Child c4 = (Child)p2; // 81: Ok.
2: Ok. Every Child IS-A parent.
3: Compile time error. A Parent object is not a Child.
4: Ok.
5: Ok, because every Child IS-A parent, and the cast is unnecessary. (Though since 3 is illegal a compile time we wouldn't actually have this situation.)
6: Ok, and the cast is unnecessary, because every Child IS-A Parent.
7: ClassCastException at runtime. The object is not a Child.
8: Ok.

Similar Messages

  • Inheritance problem with parent class calling child class

    I have a problem with inheritance with a parent class calling a child class method. Below is the example pseudocode code and my problem:
    public abstract class A {
        protected void function1 ( ) { }
        protected void function2 () {
             //calls function1();
    public abstract class B extends A {
        protected void function1 ()  {
             // do stuff
    public class C extends B {
        protected void function1 ()  {
            // do stuff
            super.function1 ();
    }I have an object instance of class C created and its function2() is invoked.
    My problem is, while in function2(), which belongs to abstract class A and the method call to function 1() is called, the call invokes the function1() of class B. Shouldn't the call invoke function 1() of class C instead? And then function1() of class B will be called after due to the super.function1(). It's not behaving like I thought it would.
    Edited by: crono77 on Jan 10, 2008 8:13 PM

    Nevermind, i found my error :)

  • Child-class refering to other Child-classes

    I am an inexperienced Java-programmer who have recently given the following some thought: if I have a Parent class that creates an instance of another class, and that class, in turn, needs to refer back to a sibling instance in the Parent class, what is the best way to go?
    I can see possibilities with creating a static method in Parent, that returns a reference to whatever other child class you might need to access. Also, I guess you could send the Parent-class to the child class as an argument, and save it in a reference-variable to use when you need to use one of the Parents non-static methods. Probably there are more possible ways.
    But what I'm asking is; which way is the most "legitime" when it comes to OOP? Surely it's butt-ugly to have a load of static methods in a Parent-class, or to propagate the Parent class through levels and levels of childs and grand-childs.
    If I haven't made myself clear -- I have doubts about my English :P -- I'll try to illustrate my question with a short code-snippet below
    Class Parent
    Child myChild;
    Sibling mySibling;
    public Parent()
    myChild = new Child();
    mySibling = new Sibling();
    // ... more follows
    Class Child
    public Child()
    // Here, I want to somehow access "mySibling" in class Parent
    // ... more follows
    // ... more follows
    Class Sibling
    // ... more follows

    As I tried to illustrate with my code snippet, the children are of separate classes. I could yet again clarify my point by giving a more concrete example, one that's the actual cause of my question.
    I have a class [MainClass] that extends JFrame, implements MouseListener, and calls its own constructor in a main()-method.
    The constructor then goes about creating the Frame's interior by creating instances of JPanels and, in one case, an extenden JPanel called CardPanel (implements ActionListener). So now we have three JPanels (including the extended) active:
    JPanel cardPanelButtons; // is the topmost panel in the frame, and lets the user switch between the different cards in the CardPanel. It contains three buttons that are in a ButtonGroup to make sure only one of them is pressed at any one time.
    CardPanel cardPanel; // is centered in the frame, and contains every interactive item in the application, except for the buttons in the cardPanelButtons-JPanel
    JPanel statusPanel; // contains a non editable JTextArea for status-messages
    CardPanel creates three panels in its constructor, and adds these to itself.
    In one of these panels (that are selected by the user, clicking on the buttons in the cardPanelButtons-JPanel) there is a "Search"-button that when pressed, performs a Database-search and then pops up the next card in the CardPanel with the apropiate query result filled in and displayed. This is all good, however for GUI-purposes, this action requires the apropiate button in the cardPanelButtons-JPanel to be "pushed" automatically when this switch between cards take place. Since these buttons are unknown to CardPanel, it needs to somehow reach them, which is where I'm starting to wonder what the best way around this is.
    Should I have the CardPanel-constructor take the parent class as an argument, and access the buttonGroup by a public getter-method in MainClass. Or should I static a public getter-method in the MainClass, letting me ignore to pass on the MainClass for reference. Should I ignore extending JPanel to create CardPanel altogether, and add everything straight into the JFrame from a MainClass-method?
    What is the most correct way, or the way programmers usually go about this type of problem?
    (In order to make myself perfectly clear, this reply is quite extensive. I apologize if I got a bit carried away..)

  • Seemingly unpredictable results when calling an overriden parent method on an instance of a child class casted to the parent class

    I have a parent class with a sub-vi, and a child which overrides this sub-vi.  I create an instance of this child.  I cast this child to it's parent class and store it in an array.  Later, if I invoke the parent's '' on this child (casted to parent) then Labview 2013 seems to randomly choose whether to run the parent or the child  In Labview 2011 SP1 it would always call the childs version of (which while surprising to me was very useful).  This has totally broken an application I have been developing, any insight as to how to control which is run would be helpful (re-casting to the child class isn't really an option, as there are in fact many child classes each with their own version of

    The actual data type of the wire is irrelevant in deciding which VI to run. The only thing that is relevant is the class of the object which is actually on the wire, so casting to the parent should not be relevant. *IF* the object really is a child, then LV should always call the child's VI, just like you say it works in 2011.
    I suspect that what's happening in your case is that somewhere you're generating a parent and that's what's actually on the wire (e.g. maybe you have an error somewhere and a function outputs the default value, which is a parent). The fact that it didn't happen in 2011 doesn't mean it's a bug in 2013. It could be that something else has changed.
    In any case, it's impossible to tell whether this is a misunderstanding, a bug in your code or a bug in LV without actual code. If you can post actual code which shows this, people can help. Otherwise (if it only happens in code you don't want to publish), you should try contacting NI directly so that you can at least show them the code.
    Try to take over the world!

  • How to get the parent window in sub-child controller class in javafx?

    how to get the parent window in sub-child controller class in javafx?

    You can get the window in which a node is contained with
    Window window = node.getScene().getWindow();Depending when this is invoked, you might want to check the Scene is not null before calling getWindow().
    If the window is a stage that is owned by another window, you can get the "parent" or "owner" window with
    Window owner = null ;
    if (window instanceof Stage) {
      Stage stage = (Stage) window ;
      owner = stage.getOwner();

  • Fastest way to create child class from parent?

    As the subject states, what do you folks find is fastest when creating child classes directly from the parent? (esp. when the parent is in a lvlib) I thought I'd post up and ask because the fastest way I've found to get working takes a few steps.
    Any suggestions ae appreciatized!

    Thanks for the quick response Ben!
    Yea, I apologize, in your response I realize my OP was more than vague haha (it hapens when you get used to your own way of doing things I guess huh)- I'm trying to create a child from a parent so that it has all of the methods that the parent has.
    In order to do so I currently have to open and close LV a few times during my current process so that vi's in memory dont get mixed up- Currently I save a copy of the parent class in a sub dir of where it is saved, close out of LV, open the new 'copy of parent.lvclass', save as>>rename 'child class.lvclass', close LV, and open up the project to 'add file', then right click>>properties>>inheritance.
    Is this the only way to do this?
    Thanks again!
    p.s. I'm tempted to steal your cell phone sig, hope you dont mind haha good stuff!

  • Why does the child class need to implement the parent classes constructor?/

    As I was playing around with some code I came across this point :
    First Class
    public class A {
         public int x;
         A(int i){
              System.out.println("A is initialised");
    }Second Class extending it :
    public class B extends A{
         private int y;
       // Why do I need this constructor to call parents constructor?
      // My guess is so that when i make an object of class B referring to class A it should make sense?
         B(int i) {                     
    public static void main(String args[]){
          A a = new A(1);
          A b = new B(1); make an object of class B referring to class A it should work!!
          B c = new B(2);
          B d =(B) new A(2);  --> gives class cast exception!
    }I am little confused here, Can someone throw more light on it.

    You don't override constructors. However, every class, in it's constructor, must call some constructor from the class it's extending. In most cases this is simply super(). However, if your class does not have a default constructor (i.e. you've declared any other constructor, or the sub class does not have access to it, I.E. you've declared it private) then you must include a call to some other constructor in the super class. The constructor in the subclass does not have to be the same as the super class one, but you do have to invoke a constructor from the super class. I.E.
    class A {
      A(int i) {}
    class B extends A {
      B(String b) {

  • Executing a child class from parent.

    Hi, well, I have this parent class which I need to execute a method from a child class to get a significant part of the thing get started. Is there anyway for me to accomplish this or a workabout? Thanks..

    Sure.. I have this method in the class logic:
         public void createLocation() {
              try {
              classCoord coordSet = appinterface.decodeFile();
              int areaNum = coordSet.areaNum, cellNum = coordSet.cellNum, signalStrength = coordSet.signalStrength, receiverId = coordSet.receiverId;
              String dateTime = coordSet.dateTime, userName = coordSet.userName, location = calLocation(areaNum, cellNum);
              boolean validity=calValidity(signalStrength);
              classLocation locationObj = new classLocation(this.type, userName, receiverId, validity, location, dateTime);
              appinterface storeLocationObj = new appinterface();
              catch (IOException ioException) {
                   appinterface.displayMessage("Logic Error: " + ioException);
              catch (ClassNotFoundException classNotFoundException) {
                   appinterface.displayMessage("Logic Error: " + classNotFoundException);
         }I need to execute this method halfway in the class appinterface, the logic class inherits from appinterface cuz I need to make use several methods from it. Is there any way to solve this somehow?

  • How to listen to user actions in child class from parent class?

    I have a basic custom class ChildCustomForm that include a JTextField. In order to know what user types, I add a listener to
    this textbox:
    textField.addKeyListener( new KeyAdapter()
                public void keyPressed( final KeyEvent e )
                    //user typed something
                    userTyped = true;
             });Now I have another parent class that uses ChildCustomForm, and parent class has to know once user types, then set
    its own userTyped flag.
    My problem is: since I added listener in child class, I cannot get textfield and add listener again in parent class, so parent class will not be able to know as soon as user types (polling is not a good solution here).
    I am wondering if there is a way to do this?

    jack_wns wrote:
    I have a basic custom class ChildCustomForm that include a JTextField. In order to know what user types, I add a listener to
    this textbox:You want to listen for input into the textbox, correct? This may take the form of keyboard input, or could be a paste-text event in which case your keylistener will miss it. I recommend that you look into a DocumentListener here so you will catch any changes, be they keyboard or cut or paste.
    My problem is: since I added listener in child class, I cannot get textfield and add listener again in parent class, so parent class will not be able to know as soon as user types (polling is not a good solution here).The observer pattern may work here.

  • Parent class not waiting for child class to finish

    i have class a and method x in class a which calls class b. its fine till there. but before my class b's action is completed, in which i have to choose a file and display those files in jtable, the remaining lines in method x getting executed. what do you think the problem is.
    i.e. my parent's class method is completely getting executed before the child class (frame) returns the result and is closed. where do u think the problem.
    please help.

    i dont know if i made myself clear. i am giving my code below.
    class A{
    pnlProductsImport _pnlProductsImport=new  pnlProductsImport(dataSource,config,parent,importFile);
    here its showing my pnlProductsImport class screen and before I close that screen, getProducts method is getting executed. as I know, the control passes from class A to pnlProductsImport at show() and when its closed, it will execute remaning lines i.e getProducts, but in this case, it shows the subclass, and immedietly, executing remaining lines. but its also fact that my subclass (pnlProductsImport) implements Runnable, but thread starts only after some time when I click on one of the buttons on the screen.... and i want that getProducts() method to execute only when subclass closes completely.

  • Cleaning up child class on parent wire

    I have a child class running on a parent wire. The parent class has a reference, and the child class has some additional references. I want to clean these up during shutdown. But, because it is a parent wire, I cannot call my child class's "destroy" method directly. Is the best way to handle this to have be dynamic dispatch, so it will call the child's destroy method via DD, and set "call parent method" to required? This way if the class is a child, it will dynamic dispatch the child's method, but force the programmer to also call the parent method? How have others handled this?
    CLA, LabVIEW Versions 2010-2013

    for(imstuck) wrote:
    Is the best way to handle this to have be dynamic dispatch...?
    Yes. That's the whole point of DD.
    Note that for cleaning up resources, the order of the cleanup might be important, so either write in such a way that it doesn't matter or document it so that the developer of the child class knows exactly when the parent destroy should be called.
    Try to take over the world!

  • JMS: how to make child class loader (classes) available to parent loader

    Environment: oc4j on SunOS 5.10
    Our application (set up in an instance other than "home") sets up a JMS receiver, everything works fine to the point where the receiver receives the message but the message deserialization fails with the below error. Looks like the deserializer (loaded by the parent classloader sytem.root) is not able to load the class from its child code-source (one of my application libraries in WEB-INF/lib) I have seen a lot of documentation on how libraries can be shared between applications, but I haven't come across any that is related to my problem here. I have even tried adding the library in question to bootclasspath that did not help either.
    How to get around this problem.
    Thanks in advance.
    Caused by: toSerializable
    at com.evermind.server.jms.JMSUtils.toSerializable(
    at com.evermind.server.jms.JMSUtils.toSerializable(
    at com.evermind.server.jms.EvermindObjectMessage.getObject(
    ... 4 more
    Caused by: oracle.classloader.util.AnnotatedClassNotFoundException:
    Missing class: com.deploy.atao.message.client.Message
    Dependent class:
    Loader: oc4j:10.1.3
    Code-Source: /export/home/oracle10as/product/
    Configuration: <code-source> in META-INF/boot.xml in /export/home/oracle10as/product/
    This load was initiated at system.root:0.0.0 using the Class.forName() method.
    The missing class is available from the following locations:
    ......( WEB-INF/lib/ directory in /export/home/oracle10as/product/
    This code-source is available in loader This is a child of the dependent loader system.root:0.0.0.
    at oracle.classloader.PolicyClassLoader.handleClassNotFound(
    at oracle.classloader.PolicyClassLoader.internalLoadClass(
    at oracle.classloader.PolicyClassLoader.loadClass(
    at oracle.classloader.PolicyClassLoader.loadClass(
    at java.lang.ClassLoader.loadClassInternal(
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(
    at com.evermind.server.ApplicationContextClassLoader.findClass(
    at java.lang.ClassLoader.loadClass(
    at java.lang.ClassLoader.loadClass(
    at java.lang.ClassLoader.loadClassInternal(
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(
    at com.evermind.server.jms.JMSUtils.toSerializable(
    ... 6 more

    Resolved by adding the application library in question to config/application.xml as <library path="<relative path to the library>"/> so the library has instance scope is accessible by the sytem.root loader.

  • Parent Child classes

    Hi All,
    I have a really general question that I have not been able to solve.
    Here is my sample code:
    class parent {
    public List mylist
    public parent(){
    child c = new child(this, mylist);
    class child
    private parent p;
    private List mylist;
    private String currentLine ="";
    public child(parent p, List mylist){
    this.mylist = mylist;
    BufferedReader in new BufferedReader(new FileReader("test.txt"));
    while ((currentLine = in.readLine()) != null){
    How do I return mylist in the child class back to the parent class? Or secondly, can I declare a List in the child class and have some way of passing it back to the parent class? I am not very familiar with the parent/child classes. If you can assist, I'd appreciate it. Thanks.

    Actually....the main problem that I have is that I am using multi threading. Right now the problem that I have is that I can't write to the same output file with multiple children threads...not sure why.
    class parent {
    PrintWriter out;
    public parent () {
    out = new PrintWriter(new BufferedWriter(new FileWriter("output.txt")));
    for (int i=0; i<10; i++){
    childthread ct = new childthread(this);
    public synchronized void Output (String output){
    }//end class parent
    class child extends Thread{
    parent p;
    public child (parent p) {
    this.p = p;
    public void run(){
    String thisLine = "test";
    }//end class child
    How can I get all of my 10 threads to write to the same file. Since my parent thread is the one with the output file, each time the child thread calls the p.Output and passes the should printout test in my output file...but it does not. Is there any reason why?
    My output file should display "test" ten times. Please let me know what I am doing wrong...or how I can go about writing multiple threads to the same output file. Thank you.

  • Can I make methods which are public in a parent class into private in a child class ?

    I suspect the answer to my question is probably no, but...
    I have a parent class that provides several general purpose methods, I also have a child class which is intended to provide a more specific set of methods for manipulating the data in the class. As a result, calling some of the parent's methods on the child class can provide results that I'd rather not let the users of the child class have to worry about. It seemed (from my rather naive OOP experience) that the nicest way to do this would be to make access to some of the parent's public methods be private in the child class. This doesn't seem to be trivially possible.... ?
    Gavin Burnell
    Condensed Matter Physics Group, University of Leeds, UK

    Hi Gavin,
    Unfortuneately I don't think this can be done. You can use an overide VI to change the functionality of a method in a child class but it has to have the same scope and the method it overides.
    Jon B
    Applications Engineer
    NI UK & Ireland

  • Parent class private data accessable in Child class?

    I thought that this would be obvious, but my search foo fails me.  Hopefully someone would be kind enough to answer my newbie LVOOP question.
    I have a a parrent class.  This parrent class contains a cluster of class private data.  I setup all the accessor methods to this data.  I create a child class that has functions that need to access data stored in its parrent class.  Its inheritence is set, but when I try to unbundle the class data all I can seem to get to is what is setup in the child class' data cluster.
    I've watched a video and it looked like the data cluster magically appeared and was accessable through the children methods.  What am I missing?
    Thanks for input!
    Go to Solution.

    Nickerbocker wrote:
    Well, that makes sense.
    One other quick question.  Is the procedure, New->"VI for Override..." from the context menu of my child class the only way to create a method that overrides the parents method?  Where is the property that defines this newly created VI as overriding my parent's VI?  Can I simply create a VI that is named the same and it have the same effect?
    That is the only method I use but I believe if you get all of your icon patterns and terminal marking as dynamic and all of the other rules, you should be able to do the same thing by hand (I base this guess on the fact I messed with those things and broke my ever-rides).
    The only thing I think has to be done from the project (scripting aside) is to set-up the inheritance.
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction

Maybe you are looking for

  • Installation 10g on Windows XP Home Edition

    When I try to install 10g on my Windows XP Home Edition, I get a error message, "oui.exe has encountered a problem and needs to close." Whats that all about?

  • How do i pass a daqmx task from labview to matlab using the math interface toolkit?

    I want to use DAQMX functions from Matlab using the Math Interface Toolkit (MIT). How can I have a labview function output (return) the DAQMX task to matlab via the MIT? I want to do this so I can start a DAQMX task in Labview from a matlab function

  • A D300-Work Orange (And My Apology To Adobe)

    For a long time now, I've been noticing the reds in my D300 photographs have been kinda orangy. And, I incorrectly thought Lightroom was the problem, and even got a little uppity about it on this forum, if you can imagine. After further consideration

  • Restricting Versions for Document data in MM03

    We want to restrict to users to view only the current version and some user to view all the version. Is there any option to restrict it. Request help. Regards D.Mukundan

  • Connection and Keyboard Issues (since 10.5.5 update?)

    Not quite the connection issues others are having, once Airport is connected, it stays connected. The issue is with initial connection. When I wake the Macbook up from sleep, I can't click to load anything on the internet/ in email for almost a full