• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Paul Clapham
  • Ron McLeod
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Roland Mueller
  • Piet Souris
Bartenders:

can inner class call outer class method?

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is the code;
public class Outer extends JApplet
{
private Inner top;
private JPanel face = new JPanel();
public void init()
{
getContentPane().setLayout(new BorderLayout());

top = new Outer().new Inner();
face.setBackground(Color.blue);
getContentPane().add(top, BorderLayout.NORTH);
getContentPane().add(face);
}
class Inner extends JPanel() implements ActionListener
{
JButton btn = new JButton("Button");
btn.addActionListener(this); //line one
add(btn);

public void actionPerformed(ActionEvent e)
{
face.setBackground(Color.red); //line two
}
}
}
This code can be compiled. With appletviewer, the applet can be showd. But when click the button, there is some error.
If I command out line two, the problem still there. It looks like there is something wrong with line one. If I implemented the action listener as inner class, there is no problem without line two. The button can be clicked without error. If the line two comes back, the same error is still there.
 
Ranch Hand
Posts: 155
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It depends on the accessibility of your inner class. If your inner class is non-static, it can access all the instance variables and methods of the enclosing class. This is because the inner class is bounded to an instance of the outer class. Also the inner class cannot declare any static variable or method.
If you inner class is static, which means only one copy of the inner class is available regardless of number of outer class intances. This leads to the direct accessibility of outer class's instance variable and method from the inner class. Because static inner class does not know which instance of outer class to refer to. The way around this is to declare a static outer class or by using object reference. Hope this help.
 
reply
    Bookmark Topic Watch Topic
  • New Topic