pardhasaradhy
September 23rd, 2000, 01:37 AM
How can I create an instance of an inner class?
|
Click to See Complete Forum and Search --> : java pardhasaradhy September 23rd, 2000, 01:37 AM How can I create an instance of an inner class? Phill September 23rd, 2000, 03:42 AM 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. codeguru.com
Copyright Internet.com Inc., All Rights Reserved. |