Enum private methods: did everyone know this but me?

Consider the following code:class C {
    final C C1 = new C() {
        public void f() {
            g();
    private void g() {
enum E {
    E1 {
        public void f() {
            g();
    private void g() {
}It struck me that the class and the enum are structurally very similar: the class has an inner class that references a private method; the enum has a value that references a private method.
But the big difference is: the enum won't compile. Unless I change the protection on g() to "protected" or less, it throws an error.
And the bizarre part is, the error is not "g has private access" or "cannot find symbol". No, it's "non-static method g() cannot be referenced from a static context"! WTF?
I solved the mystery by utter accident, when I changed the class to class C {
    static final C C1 = new C() {
        ...That is, I made the variable referring to the instance of the inner class static. That made the class fail to compile with the same "static context" error I saw in the enum.
It took several minutes of open-mouth staring at the screen to get it: in the original class, the g() being called was not in the same object, but in the outer object. Methods of object declared in a derived class cannot get to private members, even of the same object, declared in an ancestor class: that is the meaning of the word "private". But methods of an inner class can get to private members of the outer class. So in the original class, the inner-object could not see its own g(), so it looked at the outer-object's g(); when I changed the inner-object to static, there was no outer object, and I got an error to that effect.
Enum values are basically solitary instances of static inner classes of the class representing the enum itself and so, in the same situation produce the same error message.
Oddly, the following does compile:enum E {
    E1 {
        public void f() {
            E1.g();
    private void g() {
}That is, instead of accessing g() as E.this.g(), I accessed it statically as E.E1.g(). In fact, this was the first thing I tried -- under the wrong impression that f() was static within E1, not the E1 was static within E. In retrospect, I can see why it works, but I cannot explain it properly or defend it intellectually.
Who sez Java ain't fun?
M.

It took several minutes of open-mouth staring at the
screen to get it: in the original class, the g()
being called was not in the same object, but in the
outer object. Methods of object declared in a
derived class cannot get to private members, even of
the same object, declared in an ancestor class: that
is the meaning of the word "private".There's a problem with this theory. Consider the following:
class C {
    protected String s = "C";
    public static final C C1 = new C() {
        public void f() {
            s = "C1";
            C.C1.g();
    private void g() {
        System.out.print(s);
    public void f()
        System.out.println("C.f()");
}Then a main method like so:
    public static void main(String[] args) {
        try {
            C.C1.f();
        } catch (Exception exception) {
            exception.printStackTrace();
output:
[pre]
C1This can be changed to:
    public static final C C1 = new C() {
        public void f() {
            s = "C1";
            ((C)this).g();
    };To acheive the same effect. You can make C1 an instance, but you cannot run the example because it will throw a StackOveflow exception.
So to run the original example, we have to Change C to:
class C {
    static int count;
    protected String s = "C";
    public C()
        if (count++ < 2) C1 = new C() {
            public void f() {
                s = "C1";
                ((C)this).g();
        else C1 = null;
    public final C C1;
    private void g() {
        System.out.print(s);
    public void f()
        System.out.println("C.f()");
}now the main body becomes:
new C().C1.f();Output:
C1So the point is that the method is not called on the outer instance. The problem is with access and how the compiler is creating the code to fuflill the syntactic sugar of inner classes and nested classes.
One rule says the subclass doesn't have access to call the g() method defined in the parent class. The other rule says that it does because it's an inner class. So C1 can call g() on a C instance but not on an instance of it's anonymous class. This is a contradiction as the anonymous class instance is a C. Whether this follows the JLS (therefore not a bug) I think it's still a flaw. Try casting C1 to a C in the enum example and see if it resolves the issue.

Similar Messages

  • Drawing attention to an FP object DId YOU know this?

    Often when we are walking a user through filling out some required information we want to direct their attention to a particular control. The traditional wasy of oing this is to use "key focus" and if more "help" is required maybe change a string control with instruction saying "please fill in your name!". If you really want to get fancy you may even change the background color.
    There is now a new approach available but I am not going to tell you what it is (yet). Instead I'll show you!
    Run the attached VI (in LV 8.6) and press the highlight button.
    The approach I used is in the code but I hid it so you can first ask yourself "how would I have done that?"
    So did YOU know this? 
    Ben
    PS To find the answer in the code, please rember that I don't use sequence structes unless I have a reason.
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction
    Solved!
    Go to Solution.
    Attachments:
    Highlight.vi ‏9 KB

    sth wrote:
    From reading between Darren's lines, the method existed previously and thus if Ben saves a copy for previous versions it will work and the method can be cut and pasted to VIs and used in other versions.  Ben, can you save a version 8.5 of this and see if it works and then post it?  It would be a nice tool and some of us are stuck at 8.5 until further notice.
    Oww you are sharp Scott!
    Here it is saved as a invoke node. I did not test it since my 8.5 and 8.6 machines are unique boots of the same machine. If it works we may be able to go bak fartehr than 8.5.
    Let me know if it works!
    Ben
    Message Edited by Ben on 01-29-2009 07:56 AM
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction
    Attachments:
    Highlight.vi ‏6 KB

  • Did you know this was up on FB?

    Did you know this was up on FB? https://www.facebook.com/events/1590846764481403/1​593647247534688

    You are absolutely right, it is good business practice to check out the offerings from a company before you show or give it to your customers.
    I guess I just assumed that there would be a cut-out on the front cover of the Aperture books, since the soft cover books I ordered from iPhoto did have the front cover cut-out.
    My question, however, is where in the description of the Aperture hard cover book does it state that the cover photo is pasted on ? It is difficult to tell how the front cover is constructed from the photos on the Aperture web site.
    ...... I may have missed it.
    A lesson learned!
    Thanks for your comments.

  • Something happened to my phone and lost all contacts.I did not know this and backed up my phone.When i tried to restore back up the contacts were still not there.How to access older back up?

    Something happened to my phone and lost all contacts.I did not know this and backed up my phone.When i tried to restore back up the contacts were still not there.How to access older back up?

    Her contacts would be wherever she put them
    The iphone is designed to be synced to your computer or cloud service regularly.  If she failed to do this, then they are likely gone.

  • Another account user is using my apple id as their rescue email. Apple know this but expect me to contact him directly rather that let lim know his error. Seem strange and a recipe for conflict. What do you think?

    Another apple account user has put my apple id as their rescue email. Apple know this but expect me to contact him directly rather that let lim know his error. Seem strange and a recipe for conflict. What do you think?

    Primary and alternate email addresses need to be verified but a rescue email address doesn't, it can be added to an account and used without being verified (you will get a verify button when adding/changing it, but the system doesn't force it to be verified). I would hope that the person using the email address as their rescue email address will notice that they aren't getting reset emails and that after contacting Support to get their security questions / password reset he/she will check what they've set it to and change it. The OP won't be able to log into the other account as he/she won't know its primary or alternate ids.

  • Did you know this about bridge?

    I'm just curious if I'm the only one who is this slow... :p
    But did you know you could use Bridge to search your computer for images by dimensions? Man, I spent sooo much time this morning trying to find a way to 'trick' Windows into giving me a search by dimensions option. :D
    Afterwards, I wasted even
    more time googling for utilities or tools with that feature. :\ Then it hit me: I remembered seeing all kinds of neat bits of image information in Bridge last time I used it.
    And there it was, in the "find" menu... lol

    You are absolutely right, it is good business practice to check out the offerings from a company before you show or give it to your customers.
    I guess I just assumed that there would be a cut-out on the front cover of the Aperture books, since the soft cover books I ordered from iPhoto did have the front cover cut-out.
    My question, however, is where in the description of the Aperture hard cover book does it state that the cover photo is pasted on ? It is difficult to tell how the front cover is constructed from the photos on the Aperture web site.
    ...... I may have missed it.
    A lesson learned!
    Thanks for your comments.

  • Did you know this?

    I ordered my first book from Aperture. I was surprised to find out that the front cover of the book is not actually a "cut-out", but a photo PASTED on. This looks terrible. I would imagine that the corners of this cover photo will eventually curl up, causing the photo to come off the cover. The soft cover book that I had ordered from iPhoto (in the past) had a "cut-out on the cover, showing the photo underneath. I assumed that the Aperture book would do the same.
    Is this type of "pasted-on" photo cover explained somewhere in the ordering information that I missed???
    I can't give this to my customer.

    You are absolutely right, it is good business practice to check out the offerings from a company before you show or give it to your customers.
    I guess I just assumed that there would be a cut-out on the front cover of the Aperture books, since the soft cover books I ordered from iPhoto did have the front cover cut-out.
    My question, however, is where in the description of the Aperture hard cover book does it state that the cover photo is pasted on ? It is difficult to tell how the front cover is constructed from the photos on the Aperture web site.
    ...... I may have missed it.
    A lesson learned!
    Thanks for your comments.

  • "Loop invariant code motion" Did you know this and why didn't you tell me?

    I'll provide the answer if nobody replies but I'll let y'all discover this yourself.
    Have fun,
    Ben
    Ben Rayner
    I am currently active on.. MainStream Preppers
    Rayner's Ridge is under construction
    Solved!
    Go to Solution.

    elset191 wrote:
    Ben wrote:   
    If the LV compiler "sees" you have code in a loop that produce the same answer for every iteration it CAN move that code to execute before the loop.
    Can, or does?
    Just what I was about to ask.
    CLA, LabVIEW Versions 2010-2013

  • I should know this but is iLife included with Lion?

    I have a 2008 iMac 24" and upgraded to Lion today, iLife 08 was installed when I received the machine and I never upgraded to iLife 09.  After upgrading this morning I was surprised to see that ILife 11 did not appear, was iLife 11 including in the Lion install?  Is there something I am missing on upgrading to the newest version of iLife.  Thanks.

    bobwild wrote:
    iLife and Lion are independent of each other. You upgraded Lion and that does not include iLife. You have to upgrade ($$$) to iLife 11 if you want it.
    With the App Store, you can now select the iLife App's you want, so if only iPhoto is needed, cost is $15

  • HT1311 i did all of this but still it say you have to switch,i already changed my country to the usa but still it won't work?!

    okay so i used my itunes card in the us store but when i enter the app store and download an app,it says "your apple id idn't valid in the saudi arabian store you have to switch to the us" & i did i switched to the us but still it says the same thing? any other solution,help?

    OS X has a new way to get drivers. Manufacturers give the latest to Apple, who keep them on their servers for automatic download/install.
    You should always try deleting and re-adding in Print & Scan prefs first. If it doesn't work, then reset the printing system:
    http://support.apple.com/kb/PH14141
    You can check the version number of current (auto-download) drivers here:
    http://support.apple.com/kb/ht3669#HP

  • Override a private method in a Base class?

    How can a subclass override a final method in its superclass.
    This code compiles cleanly.
    How is this possible?
    Or Am I overlooking any point?
    class MySuperClass{
    private final String getMessage(){
         return "hello";
    protected String getAnotherMessage(){
         return getMessage() + "world";
    class MySubClass extends MySuperClass{
    private final String getMessage(){
         return "hi";
    public String getAnotherMessage(){
       return "anothermessage";
    }

    getMessage is declared as private in the base class, and therefor cannot be overridden in any subclass.
    Edit: I think I understand the question better now. You want to know why it compiles when you think it shouldn't. It's because the private method isn't really inherited at all. Your subclass created a brand new private method of the same signature, but it's completely unrelated.

  • Im trying to reset my security questions but the reset info isnt reaching my email did anyone hve this issue and know how to fix it?

    Im trying to reset my security questions but the reset info isnt reaching my email did anyone hve this issue and know how to fix it?

    You need to contact Apple to get the questions reset, which can be done by clicking here and picking a method for your country, or if that's not an option, by filling out and submitting this form.
    (95949)

  • TS3579 I found this useful because I did not know about the effect of typing in data and that you could only drag to rearrange the data.  I had typed in data before and this had caused problems but restoring defaults did not cause correct dates to show up

    I found this  (TS3579: If the wrong date or time is displayed in some apps on your Mac Learn about If the wrong date or time is displayed in some apps on your Mac) useful because I did not know about the effect of typing in data and that you could only drag to rearrange the data.  I had typed in data before and this had caused problems but restoring defaults did not cause correct dates to show up in Finder. 

    It sounds like there are a couple things going on here.  First check if you have a successful install of SQL Server, then we'll figure out the connection issues.
    Can you launch SQL Server Configuration Manager and check for SQL Server (MSSQLSERVER) if default instance or SQL Server (other name) if you've configured your instance as a named instance.  Once you find this, make sure the service is started. 
    If not started, try to start it and see if it throws an error.  If you get an error, post the error message your hitting.  If the service starts, you can then launch SSMS and try to connect.  If you have a default instance, you can use the machine
    name in the connection dialog.  Ex:  "COWBOYS" where Cowboys is the machine name.  However, if you named the SQL Server instance during install, you'll need to connect using the machine\instance format.  Ex:  COWBOYS\Romo (where Romo
    is the instance name you set during install).
    You can also look at the summary.txt file in the SQL Server setup error logs to see what happened on the most recent install.  Past install history is archived in the log folder if you need to dig those up to help troubleshoot, but the most
    recent one may help get to the bottom of it if there is an issue with setup detecting a prior instance that needs to be repaired.
    Thanks,
    Sam Lester (MSFT)
    http://blogs.msdn.com/b/samlester
    This posting is provided "AS IS" with no warranties, and confers no rights. Please remember to click
    "Mark as Answer" and
    "Vote as Helpful" on posts that help you. This can be beneficial to other community members reading the thread.

  • I have a problem that I try to turn on the iPad 2, but he was just lighting up, but nothing is displayed. I do not know what happened, but yesterday did not do this. Thank you for your help.

    I have a problem that I try to turn on the iPad 2, but he was just lighting up, but nothing is displayed. I do not know what happened, but yesterday did not do this. Thank you for your help.

    Try reset iPad
    Hold down the Sleep/Wake button and the Home button at the same time for at least ten seconds, until the Apple logo appears
    Note: Data will not be affected.

  • How do you get your ipod touch to make a noise when people text you and to pop up on the screen my friend did something to her ipod to do this but i dont know how please help!!!!!!!!!!!!!!!!!!!!!!!!!!! its like she updated it but i already tried it!!!!!!

    how do you get your ipod touch to make a noise when people text you and to pop up on the screen my friend did something to her ipod to do this but i dont know how please help!!!!!!!!!!!!!!!!!!!!!!!!!!! its like she updated it but i already tried it!!!!!!i am very confused and want my ipod touch 4g like that please help thxns:)

    Go to Settings>Notifications and turn alerts/sounds on for the app(s) in question.  Not all apps have all options.

Maybe you are looking for

  • Problem in navigating out of the block

    Hi, There is a form created with the help of data block wizard. The form contains 4 data blocks. The entry is to be done in a way that the first threee fields are from the first data bolck and the 4th field is from the next data block. The problem I

  • Pass parameters to sql store proc?

    Is it possible to pass parameters from Crystal Report to sql store proc? I know it will prompt for paramters if the report is built based on a parameterized store proc. I am NOT talking about these parameters. I still want user to be able to select p

  • F110 - Sending CC & Paying CC

    Hi Guys, While carrying out F110 payments from one company code to the other, initially I have made the settings in FBZP for sending CC and Paying CC. In F110 while entering the parameters, under Company code, I am giving ABCD,XYZ1. I want ABCD to be

  • Generate Adobe Interactive Form in background and setpdfSource value.

    Hi, Is there any way to create Adobe Interactive Form in the background assigning R/3 data (without displaying) and assign pdfSource binary information in context attribute and later, display Adobe Interactive Form using pdfSource context attribute i

  • XMLGregorianCalendarImpl not found in AIX envirnment

    Hi, I bumped into an issue about Class Not Found Exception in AIX environment. It complains: java.lang.NoClassDefFoundError: com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl      at java.lang.J9VMInternals.verifyImpl(Native M