Java inner class access specifiers

public class MyClass1 {
public static void main(String argv[]){ }
/*Modifier at XX */ class MyInner {}
What modifiers would be legal at XX in the above code?
1) public
2) private
3) static
4) friend

Iam a newbie to javaI don't care. I still assume you have a brain and expect you to use it.
and iam struck with this
question, iam getting a compile time error for any
access specifiers mentioned as options, but the
answers given by my superior are 1,2,3, are
correct..Then you made a typo or whatever. Make sure you eliminate the problems that are not "illegal access modifier" errors.
What good is knowing the reply to this if you can't even write an example?

Similar Messages

  • JavaFX accessing Java Inner Classes

    We have LOTS of common Java classes that look like this...
    public class X {
        public class Y {
            public static final String Z = "ZzZZZzzZzzZzzZz";
    }So in JAVA we can access them like this...
    public String z = X.Y.Z;But in JavaFX I CAN'T do this...
    var z : X.Y.Z;The compiler says +"non-static class com.myproject.X.Y cannot be referenced from a static context"+
    Tell me it aint so, please :)

    Galien, I doubt AndrewHughes can / want to change all the existing Java classes...
    I tried to reproduce (I did) and found a workaround...
    Java class (X.java):
    public class X
        public static final String ZX = "ZzZZZzzZzzZzzZzXX";
        public class Y
            public static final String ZY = "ZzZZZzzZzzZzzZzYY";
        public static void main(String[] args)
          new A();
    class A
      A()
        System.out.println(X.Y.ZY);
    }OK, it works...
    JavaFX code: var z = X.Y.Z;(and not var z: X.Y.Z; since Z isn't a type...) Error "+non-static class X.Y cannot be referenced from a static context+". Mmmm...
    Trying var z = X.ZX; works, of course.
    Looking at the generated class files, I thought of a workaround: var z = X$Y.ZY;Yay! it works! :-D

  • Java inner classes

    G'day
    How does one - in CF - refer to an inner class (ClassFoo.Bar)
    of a given
    class (ClassFoo), when the constructor of ClassFoo takes an
    argument of
    type ClassFoo.Bar?
    For example the first, third,fourth and fifth constructors
    shown here:
    http://tinyurl.com/hfg9s
    (org.apache.lucene.document.Field).
    Any ideas?
    Adam

    >is the reason you can't use another "." because it is not
    a property of Field
    Thats my understanding, yes.
    > what does the $ represent
    Its part of the class name. It has to do with how java
    compiles the classes. It creates one file for the outer class and
    one for the inner class. The naming convention for inner class
    files is usually "OuterClassName$InnerClassName.class". So the
    class name passed to createObject() becomes
    bar = createObject("java", "OuterClassName$InnerClassName");

  • Inner class access to its creator

    Hi there,
    From a subclass of Action I have created as a (non-static) inner class of a JFrame, I wish to reference the parent JFrame in a JFileChooser invocation, so something like:JFileChooser.showSaveDialog(**this**);with **this** being the parent JFrame.
    One option I can think of is to pass through "this" when I instantiate the action, but I wondered if there was a language construction that provided this information directly.
    I tried a search through the forums using "parent of an inner class" but found nothing useful. Is there a mechanism to provide this, or is passing "this" through to the inner class the only option?
    Thanks for any help you can provide.
    Tim

    To access wrapper instance of inner class, you can use WRAPPER_INSTANCE_CLASS.this keyword.
    For example:
    public class a {
       int value = 0;
       public void doSomething() {
          Object dummy = new Object() {
              public String toString() {
                  a.this.setSomething(10);
                  return a.this.toString();
          System.out.println(dummy);
       public void setSomething(int x) {
          value = x;
       public String toString() {
          return "class a, the value now is " + value;
       public static void main (String s[]) {
           new a().doSomething();
    }note that I use a.this.setSomething(10);
    a is the wrapper class, so a.this refers to the wrapper instance, not current instance.
    rgds,
    Alex

  • Inner class access to outer class variables

    class X extends JTextField {
    int variable_a;
    public X() {
    setDocument(
    new PlainDocument() {
    //here i need access to variable_a
    i don't want to make variable_a a static member though, so does anyone know how to do it?

    Generally, you can reference your variable_a just as you would any other variable except if your inner class also defines a variable_a. However, to produce a reference to the enclosing outer class object you write "OuterClassName.this". So, to get to your variable I think you would write "X.this.variable_a". I hope this helps.

  • Java Inner classes within the Threading paradigm

    Hi all.
    Im familiar with static nested classes, method local classes, inner classes and anonymous classes.
    But what I am a little perplexed by, is when exactly to use inner classes or static nested classes? (forgetting anonymous classes and method local classes).
    I read this article (http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html) and the first point makes for a good argument, but why nest the class? Why not define it as an external class?
    Also you typically find nested classes within the Threading paradigm, but why?
    I typically would create a top level class (non nested) that would implement the Runnable interface, override run() and then
    use this class when constructing a new Thread.
    Any clarification would be greatly received.
    Thanks and Happy Friday.

    Boeing-737 wrote:
    I read this article (http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html) and the first point makes for a good argument, but why nest the class? Why not define it as an external class?
    I was going to provide some reasons, but when I read the article I found they were already there. Following the DRY principle I'm going to let the article speak for itself.
    Also you typically find nested classes within the Threading paradigm, but why?No, I don't. If that's where you typically find them then you haven't had a varied experience.
    I typically would create a top level class (non nested) that would implement the Runnable interface, override run() and then
    use this class when constructing a new Thread.So carry on doing that, if it works for you.

  • Java package class access

    Hi All,
    I have two packages in a webapplication. com.mycompany.myapp and com.mycompany.myapp.classbank.
    I set up the application so I have a package for re-usable classes(myapp.classbank) and the other for the backing beans for my pages and the session bean and application bean etc(myapp).
    I can get access to any objects methods from the classes in myapp but I cannot get access to the methods in say the sessionbean from the classbank classes.
    Code completion shows access to the sessionbeans methods but I always get a null pointer exception when the app is run / debugged.
    Any insight would be most helpful.
    Regards
    Jim

    Thanks All,
    I can access any of the sessionbeans variables through the public getters and setters from any other class in the same package. If I try to access any of the same member variables from any class in the second package I get the null pointer... I can see each time the line of code that throws the exception. Its always the first line of code to try to access a getter or setter in the session bean from the second package.
    An example error (Tomcat 5.5.17 NetBeans 5.5) from today below :
    Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
    at com.sun.faces.el.MethodBindingImpl.invoke(MethodBindingImpl.java:150)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:92)
    ... 29 more
    Caused by: java.lang.NullPointerException
    at com.mycompany.imageshop.classbank.ShoppingBasket.setNumberOfPictures(ShoppingBasket.java:498)
    at com.mycompany.imageshop.viewBasket.incSmallQuantityButton_action(viewBasket.java:1094)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:585)
    at com.sun.faces.el.MethodBindingImpl.invoke(MethodBindingImpl.java:146)
    ... 30 more
    Oct 15, 2007 11:36:24 AM org.apache.catalina.core.ApplicationContext log
    SEVERE: #{viewBasket.incSmallQuantityButton_action}: javax.faces.el.EvaluationException: java.lang.NullPointerException
    javax.faces.FacesException: #{viewBasket.incSmallQuantityButton_action}: javax.faces.el.EvaluationException: java.lang.NullPointerException

  • Java servlet class access

    Can a servlet running on server A access a class defined on server B?
    More information:
    I am new at Java servlet programming and want to make sure that my web application is secure. I have set up a Java class that returns some user information (name, email address etc) and I have set up some jsp and servlet pages that access the class via an 'import my.class...' for servlets and a '@page import ="my.class..." 'for jsp. The jsp and servlet pages do session checking and authentication but the class does none of that - it's methods just return the requested data. I do not want to put any authentication in the class but I want to be certain that there is no way some other web server out on the internet could access this class in my web application. I do not think it is possible but my fear is that some hacker out there could somehow remotely do an @page import "my.class..." on my webserver and then gain access to my class methods? These web apps are running inside a Glassfish 3.0 app server.
    Thanks!

    user479480 wrote:
    That is very helpful info. I have been writing a lot of functional type code (updating, selecting and returning database data etc) inside Java servlets but when I get a new requirement I end up rewriting the same code in new servlet pages. So I have been thinking of putting all of that functional code in classes that I can re-use but was unsure of the security access and did not want to clutter the classes up with a bunch of session/authentication checking.
    Do you recommend any books on J2EE Web programming? Thanks again for your assistance.Code re-use isn't a problem that way, because you can put your common code into a library jar and use it in as many JVMs as you like. What you can't do is to access any Java objects running in one JVM from another one, whether or not they are on the same machine.

  • Inner Classes Changing Access Rights Of Parent  Members

    I read that if you access a parent class's private memebers or methods from within an inner class, those members of methods will automatically and silently be converted to having package access. This seems dangerous and I'd like to know how I could design around it.
    Here is my current dilemma. I have an EventHandler class whose handleEvent() method changes with the object's state. I've implemented this using the Strategy Pattern, where the Strategy objects are inner classes of EventHandler. The problem is that these Strategy objects need access to certain private members and methods of their parent. There is no reason, however, to give package access to these members and methods. What can I do? Or does this suggest that I need a design change? Other than this issue, though, I'm quite happy with the design.
    Thanks for any thoughts,
    John

    When inner classes access private fields or methods, the compiler generates new package-private methods
    with names like "access$000":
    import java.lang.reflect.*;
    public class X {
        private void x() {}
        class Y {
            public void y() {
                x();
        public static void main(String[] args) {
            Method[] methods = X.class.getDeclaredMethods();
            for(int i=0; i<methods.length; ++i)
                System.out.println(methods.getName());
    So it's not correct that the access to fields or methods is changed, just that additional methods are added.
    Unless you're in the habit of writing method names that contain '$', I think it's unlikely that you'll directly call
    these new methods, and if you do, it should be easy to spot!

  • Method local Inner class

    Why method local class can access only the final varaible of the method?
    I found somewhere that this is because the non-final local variables go out of scope after method completion, but i wonder final local variables also reside on the stack.
    class MyOuter2 {
    private String x = "Outer2";
    void doStuff() {
    String z = "local variable";
    class MyInner {
    public void seeOuter() {
    System.out.println("Outer x is " + x);
    System.out.println("Local variable z is " + z); // Won't Compile!
    } // close inner class method
    } // close inner class definition
    } // close outer class method doStuff()
    }

    pxNet wrote:
    and so you are now saying it accesses the original variable, not a copy of it?No, I'm not saying that at all; see reply #1. The situation is quite the opposite, the inner class accesses a copy of the variable. Direct access to the local variable is most definitely not allowed. But that doesn't have anything to do with parameter-passing semantics.
    I'll try to clarify with another demonstration of the problem. Assume that direct access to non-final local variables was actually allowed, and that the following example would compile (it won't, of course): class Outer {
        Inner method() {
            Object o = "foo";
            return new Inner() {
                public void modifyLocalVariable() {
                    o = "bar";
        interface Inner {
            void modifyLocalVariable();
        public static void main(String[] args) {
            Inner inner = new Outer().method();
            inner.modifyLocalVariable(); // what local variable is this modifying?
                                         // the local variable in method() has gone
                                         // out of scope!
    }Because of the way anonymous inner and local classes are implemented, they get a copy of the local variables (per the JLS). Mind you, there isn't any parameter passing going on at all in this example.
    ~

  • My java program runs fine even if i don't specify access specifier of class

    Hi,
    My java program runs fine even if i don't specify access specifier of class as public .
    Then why do they say that atleast one class should be specified as public.
    please help.

    public access specifier is the default access
    specifier
    so if you dont give the access specifier before the
    class name it is not wrong.I think that you are wrong. The default specifier is package or "package-private".
    See here:
    http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
    Message was edited by:
    petes1234

  • How to call inner class method in one java file from another java file?

    hello guyz, i m tryin to access an inner class method defined in one class from another class... i m posting the code too wit error. plz help me out.
    // test1.java
    public class test1
         public test1()
              test t = new test();
         public class test
              test()
              public int geti()
                   int i=10;
                   return i;
    // test2.java
    class test2
         public static void main(String[] args)
              test1 t1 = new test1();
              System.out.println(t1.t.i);
    i m getting error as
    test2.java:7: cannot resolve symbol
    symbol : variable t
    location: class test1
              System.out.println(t1.t.geti());
    ^

    There are various ways to define and use nested classes. Here is a common pattern. The inner class is private but implements an interface visible to the client. The enclosing class provides a factory method to create instances of the inner class.
    interface I {
        void method();
    class Outer {
        private String name;
        public Outer(String name) {
            this.name = name;
        public I createInner() {
            return new Inner();
        private class Inner implements I {
            public void method() {
                System.out.format("Enclosing object's name is %s%n", name);
    public class Demo {
        public static void main(String[] args) {
            Outer outer = new Outer("Otto");
            I junior = outer.createInner();
            junior.method();
    }

  • How to access var in outter class inside inner class

    I've problem with this, how to access var number1 and number2 at outter class inside inner class? what statement do i have to use to access it ? i tried with " int number1 = Kalkulator1.this.number1; " but there no value at class option var y when the program was running...
    import java.io.*;
    public class Kalkulator1{
    int number1,number2,x;
    /* The short way to create instance object for input console*/
    private static BufferedReader stdin =
    new BufferedReader( new InputStreamReader( System.in ) );
    public static void main(String[] args)throws IOException {
    System.out.println("---------------------------------------");
    System.out.println("Kalkulator Sayur by Cumi ");
    System.out.println("---------------------------------------");
    System.out.println("Tentukan jenis operasi bilangan [0-4] ");
    System.out.println(" 1. Penjumlahan ");
    System.out.println(" 2. Pengurangan ");
    System.out.println(" 3. Perkalian ");
    System.out.println(" 4. Pembagian ");
    System.out.println("---------------------------------------");
    System.out.print(" Masukan jenis operasi : ");
    String ops = stdin.readLine();
         int numberops = Integer.parseInt( ops );
    System.out.print("Masukan Bilangan ke-1 : ");
    String input1 = stdin.readLine();
    int number1 = Integer.parseInt( input1 );
    System.out.print("Masukan Bilangan ke-2 : ");
    String input2 = stdin.readLine();
    int number2 = Integer.parseInt( input2 );     
         Kalkulator1 op = new Kalkulator1();
    Kalkulator1.option b = op.new option();
         b.pilihan(numberops);
    System.out.println("Bilangan yang dimasukkan adalah = " + number1 +" dan "+ number2 );
    class option{
    int x,y;
         int number1 = Kalkulator1.this.number1;
         int number2 = Kalkulator1.this.number2;
    void pilihan(int x) {
    if (x == 1)
    {System.out.println("Operasi yang digunakan adalah Penjumlahan");
            int y = (number1+number2);
            System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 2) {System.out.println("Operasi yang digunakan adalah Pengurangan");
             int y = (number1-number2);
             System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 3) {System.out.println("Operasi yang digunakan adalah Perkalian");
             int y = (number1*number2);
             System.out.println("Hasil dari operasi adalah = " + y);}
    else
    {if (x == 4) {System.out.println("Operasi yang digunakan adalah Pembagian ");
             int y = (number1/number2);
             System.out.println("Hasil dari operasi adalah =" + y);}
    else {System.out.println( "Operasi yang digunakan adalah Pembagian ");
    }

    Delete the variables number1 and number2 from your inner class. Your inner class can access the variables in the outer class directly. Unless you need the inner and outer class variables to hold different values then you can give them different names.
    In future place code tags around your code to make it retain formatting. Highlight code and click code button.

  • 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);
    }

  • Accessing member variable within an anonymous inner class

    I'm getting a compiler error with the following snippet which resides in a constructor (error below):
            final String fullNamesArr[] = new String[ lafsArr.length ];
            String lafNamesArr[] = new String[ lafsArr.length ];
            JMenuItem namesMenuItemArr[] = new JMenuItem[ lafsArr.length ];
            for ( int i = 0 ; i < lafsArr.length ; i++ )
                StringTokenizer tokenizer;
                fullNamesArr[ i ] = lafsArr[ i ].getClassName();
                tokenizer = new StringTokenizer( fullNamesArr[ i ] );
                while ( tokenizer.hasMoreTokens() )
                    lafNamesArr[ i ] = tokenizer.nextToken( "." );
                namesMenuItemArr[ i ] = new JMenuItem( lafNamesArr[ i ] );
                lafMenu.add( namesMenuItemArr[ i ] );
                namesMenuItemArr[ i ].addActionListener(new ActionListener()
                        public final void actionPerformed(final ActionEvent e)
                            String actionCommand = e.getActionCommand();
                            int iCount = 0;
                            for ( int index = 0 ; index < fullNamesArr.length ; index++ )
                                if ( fullNamesArr[ index ].contains( actionCommand ))
                                    iCount = index;
                                    break;
                            System.out.println( "Setting LAF to '" +
                                                fullNamesArr[ iCount ] + "'" );
                            try
                                UIManager.setLookAndFeel( fullNamesArr[ iCount ] );
                            catch ( UnsupportedLookAndFeelException ulafe )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Not a valid LAF class." );
                            catch ( ClassNotFoundException cnfe )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Class not found." );
                            catch ( InstantiationException ie )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Can't instantiate class." );
                            catch ( IllegalAccessException iae )
                                System.out.println( fullNamesArr[ iCount ] +
                                                    " : Illegal access." );
    DBBuilder.java:1280: cannot resolve symbol
    symbol : method contains (java.lang.String)
    location: class java.lang.String
    if ( fullNamesArr[ index ].contains( actionCommand ))
    ^
    1 error
    BUILD FAILED
    My question: Why can I access fullNamesArr in other spots in the anon-inner class,but not with the String.contains() method? BTW, the carrot is under the left bracket '['.
    TIA,
    Jeff

    My question: Why can I access fullNamesArr in other
    spots in the anon-inner class,but not with the
    String.contains() method? BTW, the carrot is under
    the left bracket '['.You're misinterpreting the message. The problem is not your variable fullNamesArr, but rather the method contains(java.lang.String). Since that method was only added in Java 5 (aka 1.5) you might look if you're compiling with JDK 1.4 or earlier.

Maybe you are looking for

  • List view

    How do I change to list view, so I can see everything on one line including my comments, like in the old (and far better) iTunes, please The new design is horrible!

  • Can't access the bookmarks backup file I created on my external harddrive from my desktop to restore on my laptop.

    I created a firefox bookmarks backup file from my desktop computer on my external USB hard drive so that I could transfer them to my laptop. I go to "organize bookmarks" on my laptop, choose "restore", "choose file", navigate to the external drive. A

  • Urgent: Fit to Page for Printed Version

    Hi All, I have a specific requirement from the client where they want all there web reports to fit to one page when exporting to PDF. The problem we are facing is that these are highly formatted reports and there is a mixture of report items and char

  • Error - When Activating Generic Data source in BW DEV

    Hi, I am working in BI 7.0 I created a Generic Data source I had checked in RSA3 , it is showing records too. i replicated the Datasource in BW Datasource is available in BW Then I try to activated the Datasource because when i try to create tranform

  • Create File from Variable

    I have an Image variable that is loaded with an Image. Is there a way I can stream this variable to a new file on my computer? Mediocre Access 2010 | (Baby) Beginner C Sharp | OK at Active Directory (2012) | Fragmented understanding of DNS/DHCP | Lau