Private inner classes

I'm trying to complete a "turn the lightbulb on and off" program, but when I try to draw circle2 in the
ButtonListener class I get an error message cannot find symbol. This is in reference to the Graphics
variable "page" created in the paintComponent method below. Shouldn't the inner class, private or
public inherit all data variables including objects from the parent class, in this case, the Bulb class? The code is below.
By the way, this IS NOT a school assignment so any help would be appreciated. I'm just trying to learn
this language.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Bulb extends JPanel
     private JButton push;
     private Circle circle, circle2;
     private final int DIAMETER = 100;
     private final int X = 10;
     private final int Y = 10;
     public Bulb()
          circle = new Circle(DIAMETER, Color.white, X,Y);
          circle2 = new Circle(DIAMETER, Color.yellow, X, Y); // to separate class
          push = new JButton("Turn on the Bulb");
          push.addActionListener(new ButtonListener());
          add(push);
          setPreferredSize(new Dimension(500, 500));
          setBackground(Color.black);
     public void paintComponent(Graphics page)
          super.paintComponent(page);
          circle.draw(page);
private class ButtonListener implements ActionListener
          public void actionPerformed(ActionEvent event) //PROBLEM AREA. I GET ERROR MESSAGE STATING
// "CANNOT FIND SYMBOL" IN REFERENCE TO VARIABLE "PAGE."
// I THOUGHT THE INNER CLASS INHERITS ALL DATA FROM
// PARENT CLASS SUCH AS "PAGE."
               circle2.draw(page);
}

There are fields, which are associated with either a class or an object (and thus live in the heap in an object on the heap), and there are local variables, which are associated with methods and threads (i.e., a method invoked within a thread, and which thus live on the stack).
They're not the same thing.
You can't use a local variable in your paintComponent method in a different method.
Anyway you're designing your class wrong. Think model-view-controller. You have the model: a bunch of state and possibly behavior that represents the thing being seen, modified, and displayed. You have the view, which is how you see the model. And you have the controller, which modifies the model.
Your event handlers are part of the controller. They should change the model.
Your paintComponent method is part of the view.
So the event handlers should change some data, e.g., add a note that a circle should be displayed.
Then your paintComponent method should look at the data and act accordingly -- e.g., see that there's a circle to be displayed, and display it.

Similar Messages

  • Private inner class and static private inner

    Hi,
    I understand the concept and usage of inner classes in general.
    When should we go for a private inner class and when for a static private inner class? I tried searching but it wasn't of much help.
    Basically I need to design a caching solution in which I need to timestamp the data object. After timestamping, data will be stored in a HashMap or some other collection. I'm planning to use a wrapper class (which is inner and private) which holds the data object and timestamp. I can make the program work by using either normal inner class or static inner class, however would like to know which is better in such case. Also If I can get some general guidelines as to when to use a staic inner class and when to use a normal inner class, it would help me.
    Thanks in advance.

    user1995721 wrote:
    When should we go for a private inner class and when for a static private inner class?
    I can make the program work by using either normal inner class or static inner class, however would like to know which is better
    If I can get some general guidelines as to when to use a static inner class and when to use a normal inner class, it would help me.Making the inner class static is helpful in that it limits visibility.
    If the inner class needs to access non-static fields or methods from the containing class instance
    the inner class has to be non-static.

  • Creating Private Inner Classes in Separate Files

    I sometimes find myself wanting to use private inner classes to do things, but then moving the classes to separate files and giving them package access just because I don't like having single large files.
    Is there a way to create private inner classes on a class but just save them in another file?
    Thanks,
    John

    For me, short file sizes usually make design structure
    more clear. This can make maintenance easier. It can
    also make browsing the code easier, even if you have a
    good editor or IDE. It is also less intimadating
    psychologically (for me, anyway) to work with a number
    of small files, each one with a distinct purpose, than
    it is to open up a monster, even if the monster does
    represent a coherent design unit in some sense. I
    think this psychological impact may be more important
    than most people give it credit for.The psychological impact is lessened if you use an IDE like VisualAge (where only one method at a time is generally displayed) or use the "Show Source Of Selected Element Only" option in Eclipse.
    It's one thing to say a method should be short and a class should have as few methods as possible. Those forces reduce complexity and ease maintenance. It's another to say a source file should be short. A source file is just a storage artifact; source code could be stored in a database without changing how the programmer interacts with it. The fact that the standard java compiler requires the implementation of nested classes to be stored inside the source file of their containing class is a minor inconvenience. Don't let it discourage you from using inner classes when they make sense. The design should not be driven by source file size considerations.
    >
    But you have added code only with the sole intent of
    making a source file smaller. If Java had amechanism
    for storing nested classes in other files youwouldn't
    do this. My point below was that you shouldn't let
    source file size override the decision to use anested
    class.Why shouldn't I let it? There are plenty of
    non-trivial benefits (the ones I gave above, for
    starters) to working with smaller files.Because all of those benefits can be gained from using a decent IDE. Eclipse is free. It can show only the current method and it can collapse nested classes.
    You say "If
    Java had a mechanism...." Well, I could answer: It
    does have such a mechanism, and that mechanism is
    packages.Packages are not a mechanism for creating private inner classes in separate files. Eclipse has a mechanism for making the fact that they reside in the same source file a non-issue.
    >>
    I am not being cavalier. I have no argument, onlyan
    opinion.Again, you are perfectly entitled to your opinion.
    But if it is truly an opinion, and nothing more, why
    bother telling me about it. You might as well post
    your favorite color. It is the reasons for your
    opinion that interest me, and you still have not
    really given any.I have had lengthy arguments about the issue of method and class size. Like I said before, I prefer very small classes and methods. I also think the number of nested classes should be as small as possible. But I have no problem with large files. Files are just one way to organize source code. The size of the things in the files matters, not the files themselves.

  • Private inner class

    I have a private inner class , the methods and constructor of this inner class should be private or default ?Please explain me what is the right method and constructor access modifier I should use to private inner classes .

    paulcw wrote:
    I believe that if you make the constructor private, nothing can instantiate it.Not true for an inner class.
    Re the original question: I'm not sure it really matters here, but I've not seen a canonical answer to this.

  • Compiler bug with generics and private inner classes

    There appears to be a bug in the sun java compiler. This problem was reported against eclipse and the developers their concluded that it must be a problem with javac.
    Idea also seems to compile the example below. I couldn't find a bug report in the sun bug database. Can somebody tell me if this is a bug in javac and if there is a bug report for it.
    https://bugs.eclipse.org/bugs/show_bug.cgi?id=185422
    public class Foo <T>{
    private T myT;
    public T getT() {
    return myT;
    public void setT(T aT) {
    myT = aT;
    public class Bar extends Foo<Bar.Baz> {
    public static void main(String[] args) {
    Bar myBar = new Bar();
    myBar.setT(new Baz());
    System.out.println(myBar.getT().toString());
    private static class Baz {
    @Override
    public String toString() {
    return "Baz";
    Eclipse compiles and runs the code even though the Baz inner class is private.
    javac reports:
    Bar.java:1: Bar.Baz has private access in Bar
    public class Bar extends Foo<Bar.Baz>
    ^
    1 error

    As I said in my original post its not just eclipse that thinks the code snippet is compilable. IntelliJ Idea also parses it without complaining. I haven't looked at the java language spec but intuitively I see no reason why the code should not compile. I don't think eclipse submitting bug reports to sun has anything to do with courage. I would guess they just couldn't be bothered.

  • Private inner class with private constructor

    I read that if constructor is public then you need a static method to create the object of that class.
    But in the following scenario why I am able to get the object of PrivateStuff whereas it has private constructor.
    I am messing with this concept.
    public class Test {
          public static void main(String[] args) {          
               Test t = new Test();
               PrivateStuff p = t.new PrivateStuff();
          private class PrivateStuff{
               private PrivateStuff(){
                    System.out.println("You stuff is very private");
    }

    A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
    * Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor. [Java Language Specification|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.1]
    Your main method is within the body of the top level class, so the type (the inner class) and method are accessible.
    eg:
    class ImInTheSameSourceFileAsInnerAccessTest {
        public static void main(String[] args) {          
            InnerAccessTest t = new InnerAccessTest();
            InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
    public class InnerAccessTest {
          public static void main(String[] args) {          
               InnerAccessTest t = new InnerAccessTest();
               PrivateStuff p = t.new PrivateStuff();
          private class PrivateStuff{
               private PrivateStuff(){
                    System.out.println("You stuff is very private");
    }Result:
    $ javac -d bin src/InnerAccessTest.java
    src/InnerAccessTest.java:4: InnerAccessTest.PrivateStuff has private access in InnerAccessTest
    InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
    ^
    src/InnerAccessTest.java:4: InnerAccessTest.PrivateStuff has private access in InnerAccessTest
    InnerAccessTest.PrivateStuff p = t.new PrivateStuff();
    ^
    2 errors
    Edited by: pm_kirkham on 20-Jan-2009 10:54 added example of 'in the same source file'

  • Private inner classes, should this compile:

    class Outer
    &nbsp&nbsp&nbsp&nbspclass InnerA;
    &nbsp&nbsp&nbsp&nbspclass InnerB;
    &nbsp&nbsp&nbsp&nbspclass InnerA
    &nbsp&nbsp&nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspInnerB* m_inner;
    &nbsp&nbsp&nbsp&nbsp};
    &nbsp&nbsp&nbsp&nbspclass InnerB
    &nbsp&nbsp&nbsp&nbsp{
    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspInnerA* m_inner;
    &nbsp&nbsp&nbsp&nbsp};
    The Sun Studio 8 C++ compiler says that InnerB is not accessible from InnerA and vica-versa.
    However, both classes are members of the outer class and I would think that just like member functions, they should have access to all the declarations (prviate or not) in the outer class.
    Is the compiler correct to complain about this?
    Kind Regards,
    Dave.

    the current wording of the standard favours the Sun' s interpretation.
    gcc have gone with assuming that core language defect report 45 will be accepted which would allow this.
    see http://anubis.dkuug.dk/jtc1/sc22/wg21/docs/cwg_defects.html#45 .
    /lib

  • Help: Factory Class using Inner Class and Private Constructor?

    The situation is as follows:
    I want a GamesCollection class that instantiates Game objects by looking up the information needed from a database. I would like to use Game outside of GamesCollection, but only have it instantiated by GamesCollection to ensure the game actually exist. Each Game object is linked to a database record. If a Game object exist, it must also exist in the database. Game objects can never be removed from the database.
    I thought about making the Game object an inner class of GamesCollection, but this means that Game class constructor is still visible outside. So what if I made Game constructor private? Well, now I can't create Game objects without a static method inside Game class (static Object factory).
    Basically what I need is a constructor for the inner Game class accessible to GamesCollection, but not to the rest of the world (including packages). Is there a way to do this?

    leesiulung wrote:
    As a second look, I was initially confused about your first implementation, but it now makes more sense.
    Let me make sure I understand this:
    - the interface is needed to make the class accessible outside the outer classBetter: it is necessary to have a type that is accessible outside of GameCollection -- what else could be the return type of instance?
    - the instance() method is the object factory
    - the private modifier for the inner class is to prevent outside classes to instantiate this objectRight.
    However, is a private inner class accessible in the outer class? Try it and see.
    How does this affect private/public modifiers on inner classes?Take about five minutes and write a few tests. That should answer any questions you may have.
    How do instantiate a GameImpl object? This basically goes back to the first question.Filling out the initial solution:
    public interface Game {
        String method();
    public class GameCollection {
        private static  class GameImpl implements Game {
            public String method() {
                return "GameImpl";
        public Game instance() {
            return new GameImpl();
        public static void main(String[] args) {
            GameCollection app = new GameCollection();
            Game game = app.instance();
            System.out.println(game.method());
    }Even if you were not interested in controlling game creation, defining interfaces for key concepts like Game is always going to be a good idea. Consider how you will write testing code, for example. How will you mock Game?

  • 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?

  • Subclassing and inner classes

    Hi there,
    I have an existing class "A", supplied by a third party, that contains a private inner class "I".
    I have subclassed "A" to a new class "B" to add new functionality, and I also want to replace the inner class "I" with new behaviour. The inner class "I" is invoked by methods within "A" that I have not overridden in "B". Replacing "I" appears to be impossible under these circumstances.
    My initial experiment was to create a new inner class "I" within "B" with the same name and signature as the "I" defined within "A", so...
    Class B extends A {
    private class I {}
    The code that invokes "I" is still within "A" and so my version of the "I" class is ignored, and the original "I" is invoked instead.
    Let's be clear about this, I am not surprised by this behaviour, I'm just wondering if there is any way I can get my "I" invoked by the methods in "A". If that is indeed impossible I will have to write new methods in "B" that override the invoking methods in "A".
    I did a search on the forums using the title I gave this topic, and got some fairly close hits, but nothing seemed to quite answer my question.
    Hope that all made sense. Thanks for any help.
    Regards,
    Tim

    When a class is compiled, all the references are resolved. So in the 'A' class file, a call to method someMethod() in inner class I is resolved as
    some.package.A$I.someMethod()
    Short of replacing the A$I class file, I don't know what you can do. (I think)

  • More on inner classes

    Create a private inner class that implements a public
    interface. Write a method that returns a reference to an instance of the private
    inner class, upcast to the interface. Show that the inner class is completely
    hidden by trying to downcast to it.
    I didnot understand the last part of the question..Can anyone help me out?

    That's actually pretty clear.
    You have a public interface and a public outer class.
    The outer class has an inner class marked as private which implements the interface. It also has a method that is defined as returning something that implements the interface, which you will satisfy by returning an instance of the inner class.
    You have to show that the object you get back from the outer class's method cannot be cast to the inner class.

  • 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.

  • 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.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • I don't understand the design of inner class private member

    This is a question about the java language specification of inner classes.
    In the java langage specification document, we read
    If the member or constructor is declared private,
    then access is permitted if and only if it occurs
    within the body of the top level class (�7.6)
    that encloses the declaration of the member.
    This allows following code :
      public class PrivateTest {
        public PrivateTest()
          Hello hello = new Hello();
          System.out.println(hello.secret);
        class Hello
           private String secret = "This is a secret";
      } wherein accessing the private secret field is allowed
    from into the PrivateTest enclosing class.
    My questions are :
    a) It seems that private methods or constructors of
    inner classes have no meaning, we could also declare
    them as public. True or false ?
    b) Is there any reason that Java bypass this private
    mechanism ?
    c) Why is the above definition not written with
    "first enclosing" instead of "top level" ?
    Thanks in advance

    Private methods and constructors of an inner class can only be accessed within the outer class. Other classes can't instantiate it or use the private methods.
    You can also make your inner class private, so it is not possible to refer to the class from outside (and thereby another way of preventing it from being instantiated).
    So it does matter which access modifiers you use.
    I think top level is more precise than first enclosing, because you can have inner classes in inner classes, which are still available for the top level class (haven't tested this).

  • HELP: Inner Class vs. Private Member

    I use "javadoc -private" to create documents with inner classes. As a result, all private fields and methods, which I don't need, show up in the same document. Is there any way I can have inner classes without private members?

    how do you declare your inner class?
    Is it (public)
    public static class MyInnerClassor (private)
    private static class MyInnerClassor (package)
    static class MyInnerClassor (protected)
    protected static class MyInnerClassTry to change the way you declare the inner class. Use protected or package or public instead.

Maybe you are looking for

  • Where can I get a new screen for my 3rd gen iPod, Where can I get a new screen for my 3rd gen iPod

    I have a 3rd generation iPod and a couple days ago I dropped it and not the screen is unresponsive to touch.. I need to know where I can get a new screen for it. The last one I bought ended up being a 4th generation one so it did not work.. Any links

  • Using Halo Template

    I need help with understanding why the menu bar in the Halo Template that I am using to construct a web page does not show. I experience a shift in the design under one of the "div" tags when I attempt to customize the image tag under the Page Title

  • Better language for email polling, C# or C++?

    There's currently a small internal debate over what language we should be writing an email polling service. It is a part of a much broader system. Various accounts will be set up, and emails will be pulled from them and then encrypted and stored in a

  • Storage Resource question

    Hi, I have a question, Can I use Storage Resources in Discrete Manufacturing? If so, is there a specific configuration for it? This question is because I have Discrete Manufacturing in my plant and there is a process where I have to make a liquid bas

  • Getting Started Advice Needed

    Hi, I have just started to look into Mac development using XCode. I am a Windows developer with a Visual Basic background until about 2.5 years ago when I switched to C#, I also have some java experience but not that strong. Most of the time I will g