CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: java

  1. #1
    Join Date
    May 2000
    Posts
    5

    java

    How can I create an instance of an inner class?


  2. #2
    Join Date
    Sep 2000
    Location
    Melbourne --> Australia
    Posts
    68

    Re: java

    Hi
    This is one way:

    public class Outer {
    public static void main(String[] args){
    new outer();
    }
    public outer(){
    Inner in = new Inner();//create instance and "in" is a reference to this instance
    }
    class Inner { //start Inner class
    }//end class Inner
    }//end class Outer




    another common way is in the parameter of
    a constructor calling another class.
    For example if you create a JTable and
    you want to do specific things with it
    that arent standard, you have to make a
    "TableModel" so you can do this by making
    an inner class extending AbstractTableModel.
    Then to make an instance of this Model you
    can simply go:

    JTable jt = new JTable(new MyModel());

    These examples have both been calling
    "no-args" constructors. If the inner class
    has a constructor with arguments you may
    have to call it instead as there may
    not be a no-args constructor ie:
    If the inner class has a constructor
    asking for a Vector you would do
    somthing like this:

    Vector v = new Vector();
    v.add("astring");
    v.add("anotherstring");
    then after adding these Objects to the
    Vector you can send it to MyModel:

    JTable jt = new JTable(new MyModel(v));

    This creates an instance and sends info
    with it.
    If you want to refer to the instance later,
    then the first way is best as you had a
    reference variable pointing to the instance.
    ie:
    Inner in = new Inner();
    Then to call a method in the inner class:
    in.amethod();

    You could have a lesson that lasted
    for a week on this topic.
    Hope this has helped.
    Phill.




Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured