Accessing Enclosing Class Members From Inner Class Subclass

I have the following scenario that I cannot get to work. Notice the comments in B.doWork() for the problem code. In B.doWork(), how do I access m_strA?
* A.java
* Created on July 5, 2002, 2:20 PM
package Projects.InnerTrouble.Files;
public class A {
     public abstract class InnerA {
          public abstract void doWork ();
     public String m_strA;
     /** Creates new A */
     public A ()
               new InnerA() {
                         public void doWork ()
                                   System.out.println("A$InnerA$1's doWork() called!");
                                   m_strA = "Annonymous subclass of InnerA's doWork did this";
                    }.doWork();
     * @param args the command line arguments
     public static void main (String args[])
               A oTemp = new A();
               System.out.println(oTemp.m_strA);
               B.getB(oTemp).doWork();
               System.out.println(oTemp.m_strA);
class B extends A.InnerA {
     public B (A a)
               a.super();
     public void doWork ()
               System.out.println("B's doWork() called!");
               // How do I access m_strA within B's doWork() method?  The following is what I would expect to be the answer, but it does not compile
               // A.this.m_strA = "B's doWork did this";
     private static A.InnerA sm_oInnerA;
     public static A.InnerA getB (A a)
               if (sm_oInnerA == null)
                    sm_oInnerA = new B(a);
               return (sm_oInnerA);

The whole point is that B is not an inner class of A
so it does not have access to A's member variables.
Eventhough B extends an inner class of A, that does
not make B an inner class of A. That is in the JLS,
but not so elegantly as I have put it, hehe.
If B were an innerclass of InnerA, then it would
qualify to access A's member variables.OK, I think that you are finally getting through to my thick skull on this one. Let me restate and get your check-off on my understanding of the situation.
The only classes with access to A's this reference are A and inner classes of A that are found within the definition of A. So, despite the fact that A and B are in the same package (and B should have access to A's non-private members because B and A are in the same package), and despite the fact that we would normally state that B "is a" InnerA (which is an inner class of A and would have access to a reference to the A.this reference), B is not allowed access to A.this (because B "is not really a" InnerA in the same way that the anonymous implementation of InnerA "is a" InnerA). However, nothing would prevent me from giving B access to a reference of the enclosing A as long as it was done via a method of InnerA, and as long as the implementation of that method is contained in A's implementation.
Does this "access" rule realy make sense? Are you aware of the justification for this rule? Or is the justification stated in the JLS? I would think that the compiler ought to be able to figure this kind of thing out and allow it. It seems to me the fact that I defined B in the way that I did, and the fact that B "is a" InnerA, implies that I desired a fairly tight relationship to A. In fact, I desired the exact relationship that exists for the anonymous implementation of InnerA.
The following is a modified version of my original example that runs as I originally wanted it to, but works around the access rules discussed on this forum thread:
* A.java
* Created on July 5, 2002, 2:20 PM
package Projects.InnerTrouble.Files;
public class A {
     public abstract class InnerA {
          public abstract void doWork ();
          /** added to allow implementors of InnerA that are not enclosed in A's class definition to have access to the enclosing class */
          public A myEnclosingInstance ()
                    return (A.this);
     public String m_strA;
     /** Creates new A */
     public A ()
               new InnerA() {
                         public void doWork ()
                                   System.out.println("A$InnerA$1's doWork() called!");
                                   m_strA = "Annonymous subclass of InnerA's doWork did this";
                    }.doWork();
     * @param args the command line arguments
     public static void main (String args[])
               A oTemp = new A();
               System.out.println(oTemp.m_strA);
               B.getB(oTemp).doWork();
               System.out.println(oTemp.m_strA);
class B extends A.InnerA {
     public B (A a)
               a.super();
     public void doWork ()
               System.out.println("B's doWork() called!");
               // The following is what I would expect to be the answer, but it does not compile
               // A.this.m_strA = "B's doWork did this";
               // added myEnclosingInstance() to get functionality desired above
               myEnclosingInstance().m_strA = "B's doWork did this";
     private static A.InnerA sm_oInnerA;
     public static A.InnerA getB (A a)
               if (sm_oInnerA == null)
                    sm_oInnerA = new B(a);
               return (sm_oInnerA);
}

Similar Messages

  • How to access super of enclosing class from inner class?

    Hello,
    I'd like to access Base.foo() from inner class in overridden Improved.foo(), but seem unable:
    public class InnerSuper {
         public static class Base {
              protected int foo() {
                   return 1;
         public static class Improved extends Base {
              @Override
              protected int foo() {
                   return Integer.parseInt(new Object () {
                        public String toString() {
                             return "1"+foo() ;
                   }.toString());
         public static void main(String[] args) {
              System.out.println(new Improved().foo());
    }The code above does not work, as it recursively calls Improved.foo() where I'd like it to call Base.foo(). What syntax construct should I use? Improved.this would be the same thing, Improved.super does not exist.
    I came up with a work around: adding a method baseFoo() to Improved and call that in the inner class:
       int baseFoo() {
          return super.foo();
       } but remain wondering if that is necessary?

    Indeed, Improved.super.foo() is allowed. My Eclipse syntax highlighting seems to have the same opinion as you: "are you sure you want to write that kind of code?" and leaves the read underlining for a syntax error on for just a second longer.
    This is where I am now:
         public static class DeferredExecSubroutineCall extends SubroutineCall {
              RelayExecutor relay;
              public DeferredExecSubroutineCall(RelayExecutor relay) {
                   this.relay = relay;
              @Override
              protected String execute(final IFDSOC fd, final String commandText) {
                   Future<String> f = relay.submit(new Callable<String>() {
                        @Override
                        public String call() throws Exception {
                             return DeferredExecSubroutineCall.super.execute(fd, commandText);
                   try {
                        return f.get();
                   } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                   } catch (ExecutionException e) {
                        if (e.getCause() instanceof RuntimeException) {
                             throw (RuntimeException) e.getCause();
                        } else {
                             throw new RuntimeException(e.getCause());
         }which is my current effort of adding concurrency to an existing project. I find it quite elegant but I am interested to hear from you...

  • Local variable can't be accessed from inner class ???????? Why ??????

    Plesae help, help, help. I have no idea what to do with this bug.........
    <code>
    for ( int i = 0; i <= 2; i++ ) {
    for ( int j = 0; j <= 2; j++ ) {
    grids[i][j] = new MyButton ();
    grids[i][j].setBorder(but);
    getContentPane().add(grids[i][j]);
    MyButton sub = grids[i][j];
    sub.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    if ( sub.getState() == 0 ) {
         sub = new MyButton( (Icon) new ImageIcon(imageFile));
         if ( imageFile.equals("cross.jpg") ) {
              sub.changeState(1);
         else {
              sub.changeState(2);
    </code>
    The compiler complains that "sub" is in the inner class, which is the ActionListener class, must be declared final. Please tell me what to do with it. I want to add an ActionListener to each MyButton Object in the array. Thanks ......

    OK, now I changed my code to this :
    for ( int i = 0; i <= 2; i++ ) {
      for ( int j = 0; j <= 2; j++ ) {
        grids[i][j] = new MyButton ();
        grids[i][j].setBorder(but);
        getContentPane().add(grids[i][j]);
        grids[i][j].addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            if ( grids[i][j].getState() == 0 ) {
               grids[i][j] = new MyButton( (Icon) new ImageIcon(imageFile));
              if ( imageFile.equals("cross.jpg") ) {
               grids[i][j].changeState(1);
              else {
              grids[i][j].changeState(2);
    [/cpde]
    Thanks for your advice !!!!!!
    Now the compiler says that i and j are local variables accessed from inner classes, needs to be declared final. How can I solve this then ???

  • OOABAP-How to access the protected methos from a class

    How to access the protected methos from a class..There is a built in class..For tht class i have created a object..
    Built in class name : CL_GUI_TEXTEDIT
    method : LIMIT_TEXT.
    How to access this..help me with code

    hi,
    If inheritance is used properly, it provides a significantly better structure, as common components only
    need to be stored once centrally (in the superclass) and are then automatically available to subclasses.
    Subclasses also profit immediately from changes (although the changes can also render them invalid!).
    Inheritance provides very strong links between the superclass and the subclass. The subclass must
    possess detailed knowledge of the implementation of the superclass, particularly for redefinition, but also in
    order to use inherited components.
    Even if, technically, the superclass does not know its subclasses, the
    subclass often makes additional requirements of the superclass, for example, because a subclass needs
    certain protected components or because implementation details in the superclass need to be changed in
    the subclass in order to redefine methods.
    The basic reason is that the developer of a (super)class cannot
    normally predict all the requirements that subclasses will later need to make of the superclass.
    Inheritance provides an extension of the visibility concept: there are protected components. The visibility of
    these components lies between that of the public components (visible to all users, all subclasses, and the class itself), and private (visible only to the class itself). Protected components are visible to and can be used by all subclasses and the class itself.
    Subclasses cannot access the private components  particularly attributes) of the superclass. Private
    components are genuinely private. This is particularly important if a (super)class needs to make local
    enhancements to handle errors: it can use private components to do this without knowing or invalidating
    subclasses.
    Create your class inse24 and inherit this CL_GUI_TEXTEDIT
    class in yours. You can then access the protected methods.
    Hope this is helpful, <REMOVED BY MODERATOR>
    Edited by: Runal Singh on Feb 8, 2008 1:08 PM
    Edited by: Alvaro Tejada Galindo on Feb 19, 2008 2:19 PM

  • How to access private method of an inner class using reflection.

    Can somebody tell me that how can i access private method of an inner class using reflection.
    There is a scenario like
    class A
    class B
    private fun() {
    now i want to use method fun() of an inner class inside third class i.e "class c".
    Can i use reflection in someway to access this private method fun() in class c.

    I suppose for unit tests, there could be cases when you need to access private methods that you don't want your real code to access.
    Reflection with inner classes can be tricky. I tried getting the constructor, but it kept failing until I saw that even though the default constructor is a no-arg, for inner classes that aren't static, apparently the constructor for the inner class itself takes an instance of the outer class as a param.
    So here's what it looks like:
            //list of inner classes, if any
            Class[] classlist = A.class.getDeclaredClasses();
            A outer = new A();
            try {
                for (int i =0; i < classlist.length; i++){
                    if (! classlist.getSimpleName().equals("B")){
    //skip other classes
    continue;
    //this is what I mention above.
    Constructor constr = classlist[i].getDeclaredConstructor(A.class);
    constr.setAccessible(true);
    Object inner = constr.newInstance(outer);
    Method meth = classlist[i].getDeclaredMethod("testMethod");
    meth.setAccessible(true);
    //the actual method call
    meth.invoke(inner);
    } catch (Exception e) {
    throw new RuntimeException(e);
    Good luck, and if you find yourself relying on this too much, it might mean a code redesign.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Inheriting from inner classes

    TIJ has a section on inheriting from inner classes, but the author didn't illustrate a scenario. What could be the possible usage? Why would one want to only inherit the inner case, but have to initialize the outter class (which it doesn't want to inherit)?
    Example code in the book:
        //: c08:InheritInner.java
        // Inheriting an inner class.
        class WithInner {
          class Inner {}
        public class InheritInner extends WithInner.Inner {
          //! InheritInner() {} // Won't compile
          InheritInner(WithInner wi) {
            wi.super();
          public static void main(String[] args) {
            WithInner wi = new WithInner();
            InheritInner ii = new InheritInner(wi);
        } ///:~

    I've certainly never felt the need to extend inner
    classes. As far as I'm concerned, inner classes are
    great for certain uses, all of which involve them
    being private. I've yet to find a scenario where a
    non-private inner class is preferable to a 'proper'
    class.To make the outer class act as a factory. The inner class is public but the constructors are private.

  • Getting the name of outer class in an inner class

    Hi,
    I have a private inner class, something like this:
    public class OuterClass extends AnotherClass {
    public OuterClass() {
    supre();
    private class innerClass1 extends SomeotherClass {
    protected void someMethod() {
    // how to get the name of outer class, that is, "OuterClass"
    Can someone please tell me how to get the name of the outer class inside the inner class method?
    Thanks in advance..
    Prasanna

    getClass().getEnclosingClass().getName()But then, you already know it, don't you?

  • Access from inner class

    hi all,
    I have one frame with two panels inside, code likes the following:
    public class ShowChart extends JFrame{
    Container f = getContentPane();
    f.setLayout(new BorderLayout());
    JPanel chart=new drawChart();
    JPanel setting=new settingChart(chart);
    f.add(setting,java.awt.BorderLayout.WEST);
    f.add(chart);
    class drawChart extends JPanel(){
    setTableWidth(int w){...}
    class settingChart extends JPanel(){
    drawChart chart;
    pubic settingChart(drawChart c){
    chart=c;
    JTextField width = new JTextField("9",4);
    add(width);
    JButton change = new JButton("Change");
    change.addActionListener(new changeHandle(chart));
    add(change);
    change.addActionListener(new ActionListener()
    public void actionPerformed(ActionEvent event){
    int w = (int)Double.parseDouble(width.getText());
    chart.setTableWidth(w);
    Compilling error: local virable chart is accessed from within inner class, need to be declared as final. chart.setTabelWidth(w);
    how can i deal with this problem? (i know it will be ok if i messy all the viriables and method of settingChart into the ShowChart class, but it seems not a nice way...)
    thanks
    dejie

    Below is an example of an inner class field 'masking' the name of the outerclass field. So to access the outerclass you use OuterClass.this and then the field of that class...
    public class OuterClass {
      private int value = 1;
      class InnerClass {
        int value = 2;
        public InnerClass() {
          doStuff();
        void doStuff() {
          this.value++;
          OuterClass.this.value++;
    }Hope that helps...

  • Setting variables from inner class

    I have a GUI that takes users information and provides a quotation as componants are clicked. My componants' Listeners are in seperate inner classes and from these I want to add certain details to variables, it seems to compile and run but it doesn't seem to be changing the value of the variable when the componants are clicked, is there any reason why this happens, my code is below:
    public class MyGUI extends JFrame{
            public MyGUI(){
              //GUI STUFF HERE
            double Price;
         private String total=calculate();
         public String calculate(){
              double aTotal=Price;
              return "$ " + aTotal;
         class MyListener implements ItemListener{
              public void itemStateChanged(ItemEvent evt){
                   if(evt.getSource()==rad1) {
                   Price=0.10;
                   else if(evt.getSource()==rad2) {
                   Price=0.12;
                        totalLab.setText(total);
    }

    shouldn't I also be able to access the outer classes methods? It doesn't seem to do this either.

  • Can enclosing instance for an inner class be null?

    I have a class Solution, which defines an inner class, SolutionStep.
    In a third class I construct several SolutionStep objects, and later use them to construct a Solution.
    In this third class I have statements like this:
    Solution solution = null;
    aCollection.add(solution.new SolutionStep(arg1, arg2);
    This has been working fine, but recently a customer reported an error,which seems to be a NullPointerException at the line above.
    Now that I look at this code, I'm not very happy about it and I'll clean it up, but I am left with the basic question of whether what I'm doing is legal. Can the enclosing instance used to construct an inner class be null? I have not been able to find a definitive answer.
    Any help appreciated.

    Yes, you're right, I dropped a parenthesis. Sorry.
    The offending statement is actually
    aCollection.add(solution.new SolutionStep(arg1,
    arg2));
    And that is certainly legal. The inner class does not
    need to be qualified when it's constructed in the
    context of an enclosing instance.Very interesting.
    The following code demonstrates this....
        class Solution
            class SolutionStep
                public SolutionStep()
        public class ThirdClass
            static public void main(String[] args)
            Solution solution = null;
            //Solution solution = new Solution();  // This produces no null exception.
            Solution.SolutionStep s = solution.new SolutionStep();
    Using jikes and javac doesn't change the behavior so that means it is VM rather than compiler specific.
    I am using 1.4.2_04 on windows and I get the null pointer exception.
    Looking at the javap output suggests that invokespecial has to be checking this (although I could have overlooked something when I checked.)
    This probably comes from the following in the VM spec under invokespecial...
    Otherwise, if objectref is null, the invokespecial instruction throws a NullPointerException.

  • Accessing the same object from multiple classes.

    For the life of me I can't workout how I can access things from classes that haven't created them.
    I don't want to have to use "new" multiple times in seperate classes as that would erase manipulated values.
    I want to be able to access and manipulate an array of objects from multiple classes without resetting the array object values. How do I create a new object then be able to use it from all classes rather than re-creating it?
    Also I need my GUI to recognize the changes my buttons are making to data and reload itself so they show up.
    All help is good help!
    regards,
    Luke Grainger

    As long as you have a headquarters it shouldn't be to painfull. You simply keep a refrence to your ShipDataBase and Arsenal and all your irrellevant stuff in Headquarters. So the start of your Headquarters class would look something like:
    public class Headquarters{
      public Arsenal arsenal;
      public ShipDatabase db;
    //constructor
      public Headquarters(){
        arsenal = new Arsenal(this, ....);
        db = new ShipDatabase(...);
    //The Arsenal class:
    public class Arsenal{
      public Headquarter hq;
      public Arsenal(Headquarter hq, ....){
        this.hq = hq;
        .Then in your ShipDatabase you should, as good programing goes, keep the arraylist as a private class variable, and then make simple public methods to access it. Methods like getShipList(), addToShipList(Ship ship)....
    So when you want to add a ship from arsenal you write:
    hq.db.addToShipList(ship);
    .Or you could of course use a more direct refrence:
    ShipDatabase db = hq.db;
    or even
    ShipList = hq.db.getShipList();
    but this requires that the shiplist in the DB is kept public....
    Hope it was comprehensive enough, and that I answered what you where wondering.
    Sjur
    PS: Initialise the array is what you do right here:
    //constructor
    shipList = new Ship[6];
    shipList[0] = new Ship("Sentry", 15, 10, "Scout");
    " " " "etc
    shipList[5] = new Ship("Sentry", 15, 10, "Scout");PPS: To make code snippets etc. more readable please read this article:
    http://forum.java.sun.com/faq.jsp#messageformat

  • Accessing a public array from extra class.

    I am trying to access a public array that I declared in my main class from a separate class. I am a bit confused about why this is not working.
    The method search in the extra class is called in the extra class in part one of the nextKeystream method. How can I get it to use the int array "key". That I declared in the MainSolitaireDriver?
    Thanks
    My main class:
    import java.util.*;
    import java.io.*;
    import java.util.Scanner;
    public class MainSolitaireDriver
       int pcount = 0;
       public int[] key = new int[26];    
       public MainSolitaireDriver()
           getValues();
            public void getValues()
                try
                    Scanner inFile = new  Scanner(new File("input.txt"));
                    for (int counter = 0; counter < key.length; counter++ )
                        key[counter]= inFile.nextInt();
                        System.out.print(key[counter]+" ");
                catch(FileNotFoundException e )
                e.printStackTrace();
                System.err.print("Failure- File Not Found");
         public static void main (String[] args)
                /*String whereInTheWorldMyFileShouldBe = new File("input.txt").getAbsolutePath();
    System.out.println(whereInTheWorldMyFileShouldBe); */
    }My extra class:
    public class Solitaire
         private Deck deck;
         *  Initialize the deck from the current key deck ordering.
         public Solitaire (int[] shuffle)
              deck = new Deck(shuffle);
            public void getArray(int[] Array)
            public int search(int [] span, int target)
                for (int indexcount = 0; indexcount < span.length; indexcount++)
                    if (span[indexcount]==target)
                        return indexcount;
            public void getArray(int[] a)
         *  Returns the next keystream generated by the Solitaire  Algorithm
         public int nextKeystream()
              // Step one: Move Joker A one card down.
                    int jokerAindex = search(MainSolitaireDriver(key), 27);
                    System.out.print(jokerAindex);
              // Step two: Move Joker B two cards down.
              // Step three: Perform a triple cut.
              // Step four: Perform a count cut.
              // Step five: Find the output card.
              return 0;
         *  Returns the ciphertext corresponding to the specified
       *  plaintext, according to the current key deck ordering.
         public String encrypt(String plaintext)
              return "";
         *  Returns the plaintext corresponding to the specified
       *  ciphertext, according to the current key deck ordering.
         public String decrypt(String ciphertext)
              return "";
    }

    Main Class
    import java.util.*;
    import java.io.*;
    import java.util.Scanner;
    public class MainSolitaireDriver
       int pcount = 0;
       public int[] key = new int[26];    
       public MainSolitaireDriver()
           getValues();
            public void getValues()
                try
                    Scanner inFile = new  Scanner(new File("input.txt"));
                    for (int counter = 0; counter < key.length; counter++ )
                        key[counter]= inFile.nextInt();
                        System.out.print(key[counter]+" ");
                catch(FileNotFoundException e )
                e.printStackTrace();
                System.err.print("Failure- File Not Found");
         public static void main (String[] args)
                /*String whereInTheWorldMyFileShouldBe = new File("input.txt").getAbsolutePath();
    System.out.println(whereInTheWorldMyFileShouldBe); */
    }Solitaire Class (not main)
    public class Solitaire
         private Deck deck;
         *  Initialize the deck from the current key deck ordering.
         public Solitaire (int[] shuffle)
              deck = new Deck(shuffle);
            public void getArray(int[] Array)
            public int search(int [] span, int target)
                for (int indexcount = 0; indexcount < span.length; indexcount++)
                    if (span[indexcount]==target)
                        return indexcount;
            public void getArray(int[] a)
         *  Returns the next keystream generated by the Solitaire  Algorithm
         public int nextKeystream()
              // Step one: Move Joker A one card down.
                    int jokerAindex = search(MainSolitaireDriver.key, 27);
                    System.out.print(jokerAindex);
              // Step two: Move Joker B two cards down.
              // Step three: Perform a triple cut.
              // Step four: Perform a count cut.
              // Step five: Find the output card.
              return 0;
         *  Returns the ciphertext corresponding to the specified
       *  plaintext, according to the current key deck ordering.
         public String encrypt(String plaintext)
              return "";
         *  Returns the plaintext corresponding to the specified
       *  ciphertext, according to the current key deck ordering.
         public String decrypt(String ciphertext)
              return "";
    }

  • Accessing an Array List from another class

    Hi, I was a member on here before, but I forgot my password and my security question is wrong.
    My question is how do I access a private arraylist from a different class in the same package?
    What I am trying to do is the following (hard to explain).
    Make a picking client for a shop, so that when an order is recieved, the picker can click on the orders button, and view all of the current orders that have not been completed. This Pick client has its own user interface, in a seperate class from where the BoughtList array is created, in the cashier client. The boughtlist is created when the cashier puts in the product number into the cashier client and clicks buy. I seem to be having trouble accessing the list from another class. Once the order is completed the cashier clicks bought and the list is reset. There is another class in a different pagage that processes some of the functions of the order, eg newOrder().
    Yes it is for Uni so I dont need / want the full answers, jist something to get started. Also please dont flame me, I have done many other parts of this project, just having trouble getting started on this one.
    Here is the code for the cashier client. The code for the Pick client is almost the same, I just need to make the code that displays the orders.
    package Clients;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.text.NumberFormat;
    import java.util.Locale;
    import Catalogue.*;
    import DBAccess.*;
    import Processing.*;
    import Middle.*;
    class CashierGUI 
      class STATE                             // Cashier states
        public static final int PROCESS  = 0;
        public static final int CHECKED  = 1;
      class NAME                             // Names of buttons
        public static final String CHECK  = "Check";
        public static final String BUY    = "Buy";
        public static final String CANCEL = "Cancel";
        public static final String BOUGHT = "Bought";
      private static final int H = 300;       // Height of window pixels
      private static final int W = 400;       // Width  of window pixels
      private JLabel      theAction  = new JLabel();
      private JTextField  theInput   = new JTextField();
      private JTextArea   theOutput  = new JTextArea();
      private JScrollPane theSP      = new JScrollPane();
      private JButton     theBtCheck = new JButton( NAME.CHECK );
      private JButton     theBtBuy   = new JButton( NAME.BUY );
      private JButton     theBtCancel= new JButton( NAME.CANCEL );
      private JButton     theBtBought= new JButton( NAME.BOUGHT );
      private int         theState   = STATE.PROCESS;   // Current state
      private Product     theProduct = null;            // Current product
      private BoughtList  theBought  = null;            // Bought items
      private Transaction     theCB        = new Transaction();
      private StockReadWriter theStock     = null;
      private OrderProcessing theOrder     = null;
      private NumberFormat theMoney  =
              NumberFormat.getCurrencyInstance( Locale.UK );
      public CashierGUI(  RootPaneContainer rpc, MiddleFactory mf  )
        try                                             //
          theStock = mf.getNewStockReadWriter();        // DataBase access
          theOrder = mf.getNewOrderProcessing();        // Process order
        } catch ( Exception e )
          System.out.println("Exception: " + e.getMessage() );
        Container cp         = rpc.getContentPane();    // Content Pane
        Container rootWindow = (Container) rpc;         // Root Window
        cp.setLayout(null);                             // No layout manager
        rootWindow.setSize( W, H );                     // Size of Window
        Font f = new Font("Monospaced",Font.PLAIN,12);  // Font f is
        theBtCheck.setBounds( 16, 25+60*0, 80, 40 );    // Check Button
        theBtCheck.addActionListener( theCB );          // Listener
        cp.add( theBtCheck );                           //  Add to canvas
        theBtBuy.setBounds( 16, 25+60*1, 80, 40 );      // Buy button
        theBtBuy.addActionListener( theCB );            //  Listener
        cp.add( theBtBuy );                             //  Add to canvas
        theBtCancel.setBounds( 16, 25+60*2, 80, 40 );   // Cancel Button
        theBtCancel.addActionListener( theCB );         //  Listener
        cp.add( theBtCancel );                          //  Add to canvas
        theBtBought.setBounds( 16, 25+60*3, 80, 40 );   // Clear Button
        theBtBought.addActionListener( theCB );         //  Listener
        cp.add( theBtBought );                          //  Add to canvas
        theAction.setBounds( 110, 25 , 270, 20 );       // Message area
        theAction.setText( "" );                        // Blank
        cp.add( theAction );                            //  Add to canvas
        theInput.setBounds( 110, 50, 270, 40 );         // Input Area
        theInput.setText("");                           // Blank
        cp.add( theInput );                             //  Add to canvas
        theSP.setBounds( 110, 100, 270, 160 );          // Scrolling pane
        theOutput.setText( "" );                        //  Blank
        theOutput.setFont( f );                         //  Uses font 
        cp.add( theSP );                                //  Add to canvas
        theSP.getViewport().add( theOutput );           //  In TextArea
        rootWindow.setVisible( true );                  // Make visible
      class Transaction implements ActionListener       // Listener
        public void actionPerformed( ActionEvent ae )   // Interaction
          if ( theStock == null )
            theAction.setText("No conection");
            return;                                     // No connection
          String actionIs = ae.getActionCommand();      // Button
          try
            if ( theBought == null )
              int on    = theOrder.uniqueNumber();      // Unique order no.
              theBought = new BoughtList( on );         //  Bought list
            if ( actionIs.equals( NAME.CHECK ) )        // Button CHECK
              theState  = STATE.PROCESS;                // State process
              String pn  = theInput.getText().trim();   // Product no.
              int    amount  = 1;                       //  & quantity
              if ( theStock.exists( pn ) )              // Stock Exists?
              {                                         // T
                Product pr = theStock.getDetails(pn);   //  Get details
                if ( pr.getQuantity() >= amount )       //  In stock?
                {                                       //  T
                  theAction.setText(                    //   Display
                    pr.getDescription() + " : " +       //    description
                    theMoney.format(pr.getPrice()) +    //    price
                    " (" + pr.getQuantity() + ")"       //    quantity
                  );                                    //   of product
                  theProduct = pr;                      //   Remember prod.
                  theProduct.setQuantity( amount );     //    & quantity
                  theState = STATE.CHECKED;             //   OK await BUY
                } else {                                //  F
                  theAction.setText(                    //   Not in Stock
                    pr.getDescription() +" not in stock"
              } else {                                  // F Stock exists
                theAction.setText(                      //  Unknown
                  "Unknown product number " + pn        //  product no.
            if ( actionIs.equals( NAME.BUY ) )          // Button BUY
              if ( theState != STATE.CHECKED )          // Not checked
              {                                         //  with customer
                theAction.setText("Check if OK with customer first");
                return;
              boolean stockBought =                      // Buy
                theStock.buyStock(                       //  however
                  theProduct.getProductNo(),             //  may fail             
                  theProduct.getQuantity() );            //
              if ( stockBought )                         // Stock bought
              {                                          // T
                theBought.add( theProduct );             //  Add to bought
                theOutput.setText( "" );                 //  clear
                theOutput.append( theBought.details());  //  Display
                theAction.setText("Purchased " +         //    details
                           theProduct.getDescription()); //
    //          theInput.setText( "" );
              } else {                                   // F
                theAction.setText("!!! Not in stock");   //  Now no stock
              theState = STATE.PROCESS;                  // All Done
            if ( actionIs.equals( NAME.CANCEL ) )        // Button CANCEL
              if ( theBought.number() >= 1 )             // item to cancel
              {                                          // T
                Product dt =  theBought.remove();        //  Remove from list
                theStock.addStock( dt.getProductNo(),    //  Re-stock
                                   dt.getQuantity()  );  //   as not sold
                theAction.setText("");                   //
                theOutput.setText(theBought.details());  //  display sales
              } else {                                   // F
                theOutput.setText( "" );                 //  Clear
              theState = STATE.PROCESS;
            if ( actionIs.equals( NAME.BOUGHT ) )        // Button Bought
              if ( theBought.number() >= 1 )             // items > 1
              {                                          // T
                theOrder.newOrder( theBought );          //  Process order
                theBought = null;                        //  reset
              theOutput.setText( "" );                   // Clear
              theInput.setText( "" );                    //
              theAction.setText( "Next customer" );      // New Customer
              theState = STATE.PROCESS;                  // All Done
            theInput.requestFocus();                     // theInput has Focus
          catch ( StockException e )                     // Error
          {                                              //  Of course
            theOutput.append( "Fail Stock access:" +     //   Should not
                                e.getMessage() + "\n" ); //  happen
          catch ( OrderException e )                     // Error
          {                                              //  Of course
            theOutput.append( "Fail Order process:" +    //   Should not
                                e.getMessage() + "\n" ); //  happen
    }

    (disclaimer: I did not read through your Swing code, as I find that painful)
    My question is how do I access a private arraylist from a different class in the same
    package?Provide a public accessor method (getMyPrivateArrayList())

  • Inheriting Context members from super class

    I have a class which extends an abstract class. That abstract
    class creates the SQLJ context members (protected members). So
    the subclasses can use the contexts. Is there any problem with
    SQLJ with this kind of approach. Because I am having strange
    problems with this.

    ...although the question reminds me of some thing that I have always liked and have not seen in any java IDEs: copy the javadoc description of some field to the getter/sett methods for that field. i.e. some thing like,
    * This field identifies a customer's unique ID in the database
    private int customerID;
    * This method returns 'customerID'.  [start copy]This field identifies....
    public int getCustomerID();

  • Python/C# class inherit from Labview Class

    Hello everyone,
    Is there any way to subclass a labview object with a class written in another langauge say python or a .net language?
    For example, I have a generic Camera.lvclass that I would like to implement for a specific camera. However, I would like to code the subclass in python. 
    My first thought was to write the python code, and then wrap it in the labview subclass using the labPython tool. Is there a better way?
    Thanks
    labjunky.

    no. a class can only inherit from one class. you can implement multiple interfaces.

Maybe you are looking for