Child-class refering to other Child-classes

Hello!
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..)

Similar Messages

  • Compiling java package class referring a default package class.

    I am trying to compile a java class having a package defination referring a java class with a default package.
    The code for the default package class is .
    public class Test{.
    public static void main(String[] args){
    System.out.println("Hello World!");
    This class compiles fine.
    I have another class called PackJava, whose code is :
    package test;
    import Test;
    public class PackJava{
    public static void main(String[] args){
    Test test = new Test();
    System.out.println("Hello World!");
    I have Test file in the windows path
    D:\development\packagetest\example
    and the PackJava java file in the path
    D:\development\packagetest\example\test
    I have set the CLASSPATH environment varibale as
    D:\development\packagetest\example;.
    When I try to compile the PackJava from the
    D:\development\packagetest\example path giving the command as
    javac -classpath . test\PackJava.java
    or
    javac -classpath %CLASSPATH% test\PackJava.java
    it gives me error,
    Do any of you have an idea of the parameter i should pass
    to the -classpath option
    Thanks

    There is a way around all this. The classes in the default packages need to implement an interface with the methods require. The interface can be in any package you want ie. com.work.around.interf.MyInterface1. Next, make this interface available in a Singleton. - The only catch here is that, the main method must reside in default package as well. And o, on start of main, instantiate the class you want and put it in the singleton. There after, you may refer to it from the singleton.
    Enjoy.

  • JAXB: How to have my generated classes subclass some other outside class ?

    With my XJS and DTD, JAXB generates the following:
    public class FraisMessage
        extends MarshallableRootElement
        implements RootElement
    { etc...I would like it to generate this instead:
    public class FraisMessage extends MyOtherClass
        extends MarshallableRootElement
        implements RootElement
    { etc...MyOtherClass is another class outside the scope of JAXB
    How do I do this ? What do I have to put in my XJS to get this ?

    You cannot do that. TheJAVA language does not allow a class to "extend" more than one upper class.
    Typically, the solution is to modify your architecture a little bit. Just use the "has a" relationship instead of "is a". That means something like that:public class MyFraisMessage
        extends MyOtherClass
        private FraisMessage message;
      etc...You write an extension "MyFraisMessage" of your upper class "MyOtherClass", which has the JAXB generated object as an attribute. This structure is often useful, when you think you would need multiple inheritance.

  • [svn:osmf:] 13027: Fix bug in SerialElement where the durationReached event was dispatched on a child-to-child transition due to the base class thinking that the duration had been reached  (since the second child didn't have a duration yet).

    Revision: 13027
    Revision: 13027
    Author:   [email protected]
    Date:     2009-12-16 18:09:46 -0800 (Wed, 16 Dec 2009)
    Log Message:
    Fix bug in SerialElement where the durationReached event was dispatched on a child-to-child transition due to the base class thinking that the duration had been reached (since the second child didn't have a duration yet).  Injection from trait refactoring.
    Modified Paths:
        osmf/trunk/framework/MediaFramework/org/osmf/composition/CompositeTimeTrait.as

    http://ww2.cs.fsu.edu/~rosentha/linux/2.6.26.5/docs/DocBook/libata/ch07.html#excatATAbusErr wrote:
    ATA bus error means that data corruption occurred during transmission over ATA bus (SATA or PATA). This type of errors can be indicated by
    ICRC or ABRT error as described in the section called “ATA/ATAPI device error (non-NCQ / non-CHECK CONDITION)”.
    Controller-specific error completion with error information indicating transmission error.
    On some controllers, command timeout. In this case, there may be a mechanism to determine that the timeout is due to transmission error.
    Unknown/random errors, timeouts and all sorts of weirdities.
    As described above, transmission errors can cause wide variety of symptoms ranging from device ICRC error to random device lockup, and, for many cases, there is no way to tell if an error condition is due to transmission error or not; therefore, it's necessary to employ some kind of heuristic when dealing with errors and timeouts. For example, encountering repetitive ABRT errors for known supported command is likely to indicate ATA bus error.
    Once it's determined that ATA bus errors have possibly occurred, lowering ATA bus transmission speed is one of actions which may alleviate the problem.
    I'd also add; make sure you have good backups when ATA errors are frequent

  • 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 Override.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 'Override.vi' on this child (casted to parent) then Labview 2013 seems to randomly choose whether to run the parent or the child override.vi.  In Labview 2011 SP1 it would always call the childs version of override.vi (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 override.vi 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 override.vi).

    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!

  • Using Inheritance,dose child class have father 's inner class?

    using Inheritance,dose child class have father 's inner class?

    as near as I can tell, the conversation so far has been:
    When I extend a class, does the subclass inherit the parent class's inner classes?
    followed by
    Never mind, i ran a test and found out the answer, sorry for my English.
    hope that helped.
    Lee

  • Compiling simultaneously two classes referencing each other

    Hi,
    When we want to compile 2 classes simultaneously in a package, we give command --
    javac package-name/*.java
    Suppose the two classes are ClassA and ClassB and ClassA has a reference of ClassB. So the compiler will finish compiling ClassB before compiling ClassA.
    But, if both the classes have each others' reference, how does compiler resolve this? Because, even in that case both classes get compiled
    Regards,
    Amit

    Lets say that compilation is done in 2 steps.
    The first step is done for all files first.
    Then the second step is done for all files.
    That means that for the second step the compile-time resolution has takes place.
    Two classes that refers to each other must go through the first step in
    the same compilation so that in the second step when
    they are referring to each other they are easily resolved.
    This is different from runtime resolution.

  • LoadClass    (error loading a class which extends other class  at run-time)

    Hey!
    I'm using the Reflection API
    I load a class called 'SubClass' which exists in a directory called 'subdir' at run-time from my program
    CustomClassLoader loader = new CustomClassLoader();
    Class classRef = loader.loadClass("SubClass");
    class CustomClassLoader extends ClassLoader. I have defined 'findClass(String className)' method in CustomClassLoader.
    This is what 'findClass(String className)' returns:
    defineClass (className,byteArray,0,byteArray.length);
    'byteArray' is of type byte[] and has the contents of subdir/SubClass.
    the problem:
    The program runs fine if SubClass does not extend any class.
    If however, SubClass extends another class, the program throws a NoClassDefFoundError. How is it conceptually different?
    Help appreciated in Advance..
    Thanks!

    Because i'm a newbie to the Reflection thing, i'm notI don't see reflection anywhere. All I see is class loading.
    sure what role does the superclass play when i'm
    trying to load the derived class and how to get away
    with the errorWell... hint: all the superclass's stuff is not copied into the subclass.
    I am quite sure it fails to load the superclass because of classpath issues.

  • How can I compile and run other java classes from within an application?

    Hello there everyone! I really hope that someone can help me. I am writing a program that must be able to compile and run other java classes that are in different files, much like development environments like Kawa or Forte allow you to do.
    There has to be a way of doing this ( I hope!! ), but i can't seem to find it!!
    I have tried using this command to compile:
    Runtime.getRuntime().exec ("c:\\programs\\javac className.java");
    ...and this one to run:
    Runtime.getRuntime().exec ("c:\\programs\\java className");
    ...but neither works!!! I can compile and run classes that are in the same file as my application, but I can't get it to work at all for files in different directories or files.
    PLEASE, PLEASE, PLEASE help me - i've run out of ideas, and i need this to be working in 3 days!!!
    Thank you very much for any help anyone can give me, I really appreciate it!! Thanks again!!
    Adrian ( ...in distress!! )

    public class JavaCompiler{
       public static void main(String[] args)throws Exception{ //sorry bout the laziness
          if(args == null || args.length != 1){
             System.out.println("Usage: java JavaCompiler MyClass.java");
             System.exit(0);
          String className = args[0];
          Runtime rt = Runtime.getRuntime();
          Process p = rt.exec("javac " + className); //consider setting cpath for this
          p.waitFor();
          //now try to run after it is done.
          p = rt.exec("java " + className.substring(0, (className.length() - ".java".length()));
          p.waitFor();
          //do some other stuff
    }This should get you going. You may consider looking into the System.getProperty() method in order to determine the type of OS it is running on in order to findo out what command to run. I know that the sun tool listed above is nice, but by my understanding the sun tools provided are not guaranteed to stay the same. I'm no expert on this matter, but that is one of the reasons there is no API documentation for those tools. Also, I don't believe those tools come packaged with the JRE. (Of course if you are making an IDE it will be expected that the user has an sdk installed. Good luck with figuring this thing out.

  • Errors in a Java class when calling other methods

    I am giving the code i have given the full class name . and now it is giving the following error :
    Cannot reference a non-static method connectDB() in a static context.
    I am also giving the code. Please do help me on this. i am a beginner in java.
    import java.sql.*;
    import java.util.*;
    import DButil.*;
    public class StudentManager {
    /** Creates a new instance of StudentManager */
    public StudentManager() {
    Connection conn = null;
    Statement cs = null;
    public Vector getStudent(){
    try{
    dbutil.connectDB();
    String Query = "Select St_Record, St_L_Name, St_F_Name, St_Major, St_Email_Address, St_SSN, Date, St_Company, St_Designation";
    cs = conn.createStatement();
    java.sql.ResultSet rs = cs.executeQuery(Query);
    Vector Studentvector = new Vector();
    while(rs.next()){
    Studentinfo Student = new Studentinfo();
    Student.setSt_Record(rs.getInt("St_Record"));
    Student.setSt_L_Name(rs.getString("St_L_Name"));
    Student.setSt_F_Name(rs.getString("St_F_Name"));
    Student.setSt_Major(rs.getString("St_Major"));
    Student.setSt_Email_Address(rs.getString("St_Email_Address"));
    Student.setSt_Company(rs.getString("St_Company"));
    Student.setSt_Designation(rs.getString("St_Designation"));
    Student.setDate(rs.getInt("Date"));
    Studentvector.add(Student);
    if( cs != null)
    cs.close();
    if( conn != null && !conn.isClosed())
    conn.close();
    return Studentvector;
    }catch(Exception ignore){
    return null;
    }finally {
    dbutil.closeDB();
    import java.sql.*;
    import java.util.*;
    public class dbutil {
    /** Creates a new instance of dbutil */
    public dbutil() {
    Connection conn;
    public void connectDB(){
    conn = ConnectionManager.getConnection();
    public void closeDB(){
    try{
    if(conn != null && !conn.isClosed())
    conn.close();
    }catch(Exception excep){
    The main error is occuring at the following lines connectDB() and closeDB() in the class student manager. The class dbutil is in an another package.with an another file called connectionManager which establishes the connection with DB. The dbutil has the openconnection and close connection methods. I have not yet written the insert statements in StudentManager. PLease do Help me

    You're doing quite a few things that will cause errors, I'm afraid. I'll see if I can help you.
    The error you're asking about is caused by the following line:
    dbutil.connectDB();
    Now first of all please always ensure that your class names begin with capital letters and your instances of classes with lowercase letters. That's what everybody does, so it makes your code much easier to follow.
    So re-write the couple of lines at the beginning of your dbutil class like this:
    public class Dbutil {
    /** Creates a new instance of Dbutil */
    public Dbutil() {
    Now you need to create an instance of dbutil before you can call connectDB() like this:
    Dbutil dbutil = new Dbutil();
    now you can call the method connectDB():
    dbutil.connectDB();
    The problem was that if you don't create an instance first then java assumes that you are calling a static method, because you don't need an instance of a class to call a static method. If it was static, the method code would have been:
    public static void connectDB(){
    You have a fine example of a static method call in your code:
    ConnectionManager.getConnection();
    If it wasn't a static method your code would have to look like this:
    ConnectionManager connectionManager = new ConnectionManager();
    connectionManager.getConnection();
    See the difference? I also know that ConnectionManager.getConnection() is a call to a static method because it begins with a capital letter.
    Anyway - now on to other things:
    You have got two different Connection objects called conn. One is in StudentManager and the other is in Dbutils, and for the moment they have nothing to do with each other.
    You call dbUtil.connectDb() and so if your connectDb method is working properly you have a live connection called conn in your dbUtil object. But the connection called conn in StudentManager is still null.
    If your connection in the dbUtil object is working then you could just add a line after the call to connectDb() in StudentManager so that the StudentManager.conn object references the dbUtil.conn object like this:
    dbutil.connectDB();
    conn = dbUtil.conn;

  • How to convert the class in the one package to same class in the other pack

    How to convert the class in the one package to same class in the other package
    example:
    BeanDTO.java
    package cho3.hello.bean;
    public class BeanDTO {
    private String name;
    private int age;
    * @return
    public int getAge() {
         return age;
    * @return
    public String getName() {
         return name;
    * @param i
    public void setAge(int i) {
         age = i;
    * @param string
    public void setName(String string) {
         name = string;
    BeanDTO.java in other package
    package ch03.hello;
    public class BeanDTO {
    private String name;
    private int age;
    * @return
    public int getAge() {
         return age;
    * @return
    public String getName() {
         return name;
    * @param i
    public void setAge(int i) {
         age = i;
    * @param string
    public void setName(String string) {
         name = string;
    My converter lass lokks like
    public class BeanUtilTest {
         public static void main(String[] args) {
              try
                   ch03.hello.BeanDTO bean=new ch03.hello.BeanDTO();
              bean.setAge(10);
              bean.setName("mahesh");
              cho3.hello.bean.BeanDTO beanDto=new cho3.hello.bean.BeanDTO();
              ClassConverter classconv=new ClassConverter();
              //classconv.
              System.out.println("hi "+beanDto.getClass().toString());
              System.out.println("hi helli "+bean.toString()+" "+bean.getAge()+" "+bean.getName()+" "+bean.getClass());
              Object b=classconv.convert(beanDto.getClass(),(Object)bean);
              System.out.println(b.toString());
              beanDto= (cho3.hello.bean.BeanDTO)b;
              System.out.println(" "+beanDto.getAge()+" "+beanDto.getName() );
              }catch(Exception e)
                   e.printStackTrace();
    But its giving class cast exception. Please help on this..

    Do you mean "two different layers" as in separate JVMs or "two different layers" as in functional areas running within the same JVM.
    In either case, if the first class is actually semantically and functionally the same as the second (and they are always intended to be the same) then import and and use the first class in place of the second. That's beyond any question of how to get the data of the first into the second if and when you need to.
    Once you make the breakthrough and use one class instead of two I'd guess that almost solves your problem. But if you want to describe your architecture a little that would help others pin down want you're trying to do.

  • NodeList.item(i) returns every other child node

    I have used the following code to eliminate null elements from a Node.
    But somehow NodeList.item(i) only returns every other child node.
    The original Node (retNode) is:
    <getHearingDetailsByCaseNoWSResponse><hearingDetailsVO xmlns="http://vo.cis.com"><NOA/><applicationNo>sAppNo0</applicationNo><caseNo/><designation/><docID/><duration/><endTime/><hearDate/><judgeName/><natureOfClaim/><outCome/><outComeTime/><outcomeDate/><remarks/><roomNo/><sessionNo/><stEndTime/><tohCode/><typeHear/></hearingDetailsVO></getHearingDetailsByCaseNoWSResponse>
    retNode.getLength() gives 19 which is correct.
    NodeList lv2List = retNode.getChildNodes();          
    int numOfLv2 = lv2List.getLength();
    if(numOfLv2 == 0) {
         if(!hasAttribute(node)) parent.removeChild(node);
              return;
         for(int i=0; i<numOfLv2; i++) {
              Node lv2Node = lv2List.item(i);
              if(lv2Node == null || lv2Node.getNodeType() != Node.ELEMENT_NODE) continue;
              removeNullElement(lv2Node);     
         }However, lv2List.item(0) returns <NOA/> element, lv2List.item(0) returns <caseNo/>, lv2List.item(1) returns <docID/>, and lv2List.item(9) returns <typeHear/>. From item(10) to item(18) all returns null.
    I was very confused by this.
    I am using Xerces-J implementation. I have set
    System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
    Did I do something wrong or I missed out something?
    Please enlighten me.
    Regards,
    Xinjun

    When an element is removed from a list, the index of each element coming after the removed one will be one less than it was before the removal, so you will have to subtract 1from the variable "i" after you have removed an element and before you start the next cycle in order not to skip the index of the removed element:for(int i=0; i<numOfLv2; i++) {
      Node lv2Node = lv2List.item(i);
      if(lv2Node == null || lv2Node.getNodeType() != Node.ELEMENT_NODE) continue;
      removeNullElement(lv2Node);
      i--
    }

  • What is actually happenning when we are importing a class of some other pac

    Sirs,
    I have a doubt which is very basic to java,
    I want to import a class say "HashMap" to my class.
    If i put import "java.util.HashMap" or "import java.util.*;"
    Which will be better ?
    If i put "import java.util.*; " will it affect the performance?
    What is actually happenning when we are importing a class of some other package to our class
    Your help solicited,
    Sudheesh K S

    Many of your questions of this nature can be quickly answered by a search of prior posts to the forums, like this:
    http://forum.java.sun.com/thread.jspa?forumID=54&threadID=631979
    And why do you tend to post boldened text? It's harder to read.

  • How can a class listen to other class's aoutput

    I have 2 classes which are both unrelated. but i want one class to listen to the output emitted by the other class. eg, class A continuosly prints messages and these messages, i want to be there in class B ...
    Any suggestions?

    I have 2 classes which are both unrelated. but i want
    one class to listen to the output emitted by the
    other class. eg, class A continuosly prints messages
    and these messages, i want to be there in class B
    Any suggestions?Classes do not listen to other classes but objects created from the classes can listen to other objects.
    eg.
    class A {
        public void sendMessage(B b) {
           b.setMessage(String aMessageFormA);
        public static void main(String[] args) {
            A a = new A();
            B b = new B();
            a.sendMessage(b);
            b.printMessageFromA();
    }

  • Instantiation access to other java classes

    Hello,
    I have a public Java file in my package.
    I want to grant access to only classes of my choice to instantiate my class, irrespective of any package(my constructor is public itself).
    Is there any way?
    eg:
    I have MyJava.java in com.abc;
    I want to give access only to 2 classes even though other classes exist in the same package:
    YourJava1.java in com.abc; (there are other classes in this package)
    YourJava2.java in com.xyz; (there are other classes in this package)
    Thanks.

    Hi,
    I'm not sure about your depths in java knowledge... however, I'm gonna try to help you based on my knowledge...
    whenever "public" modifier will be used any case( doesn't matter if it is Class, method or attributes), it will be visible from any package level. That is the Rule. If you make your constructor as public, then it always be accessible for any class regardless the package level. Otherwise, it would defeat the purpose of "public" modifier.
    Its depends on your business logic why you are trying to do this scenario. But, there are couple of ways to solve the problem...
    Make "MyJava.java"constructor as "protected" AND move whichever class needs to have handle on it into the same package(in this case: "YourJava1.java" and "YourJava2.java"). Thats how only those classes will be able to instantiate "MyJava.java". you may have multiple constructor and one of them can be "public" so that this object also can be accessed from outside of the package...
    Another option might be - make "MyJava.java" as an Interface or an abstract class. So that you can implement it whichever class needs it. This is how you can restrict it someway...
    Hope it helps...

Maybe you are looking for