Package naming and inner classes

Hi there,
I've made up the following code :
package Class1;
class i {     
     i() {
          System.out.println("outer");     
public class Class1 {     
     static class i {          
          public i() {
               System.out.println("inner");
     public static void main(String[] args) {
          i i1 = new i();
          Class1.i i2 = new Class1.i();
}that produce output :
inner
inner
which may be a suprise !!!
My question is :
Is there anyway do declare & instantiate the "i" (with "outer") class inside the Class1 class ?

that produce output :
inner
inner
which may be a suprise !!!
My question is :
Is there anyway do declare & instantiate the "i" (with
"outer") class inside the Class1 class ?This is not in the least surprising - in fact I would be 'surprised' if the outer class were referenced in preference to the local one. Stop creating problems for yourself - don't create classes named 'i' and don't declare two classes in the same package with the same names (inner classes or not) unless there is absolutely no chance of ambiguity and if they are completely private.

Similar Messages

  • What is the relation between main class and inner classes

    hi
    i want to make a UML design and o want to know how to draw the relation betwwen the main public class and inner classes?
    and what is the relation?

    BaffyOfDaffyA wrote:
    Please keep in mind that if you spell better you will get better answers and if you add duke stars you will get better answers and if you mark the thread as a question you will get better answers. That will make it look like you are paying attention and that you really want an answer.
    My best answer based on your rather vague question:
    A minimal public class in a file named "Minimal.java" in the directory named "minimal":
    package minimal;
    public class Minimal {
    private int variable;
    public Minimal(int var) {
    variable = var;
    public int getVariable() {
    return variable;
    }This would be an example of adding an inner class:
    package minimal;
    public class Minimal {
    private int variable;
    public Minimal(int var) {
    variable = var;
    public int getVariable() {
    return variable;
    public class Inner {
    private int innerVariable;
    public Inner(int var) {
    innerVariable = var;
    public int getInnerVariable() {
    return innerVariable;
    }The inner class is exactly like any other inner class except if you are accessing it from anything else other than Minimal then you would have to add Minimal. right before Inner for example, where the Minimal class could use
    Inner inner = new Inner(5);other classes would have to use
    Minimal.Inner inner = new Minimal.Inner(5);
    See [Inner Class Example|http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html] or [Nested Classes|http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html] for more information.
    He is probably not asking what an inner class is or how to declare one in raw source code. To me he is asking how do I
    explain this relationship in a UML diagram and as UML is not and exact science and expression can vary a lot
    between UML design applications I didn't want to stab in the dark.
    @OP I would say whatever seems most logical to you and your team, write something that reads.

  • Are enums and inner classes allowed in taglib function signatures??

    Hi,
    I have a taglib with the following function definition:
    <function>
            <description>Determine if viewing a patient attribute is allowed</description>
            <name>isViewingPatientAttributeAllowed</name>
            <function-class>com.example.admin.authorization.UserAuthorizer</function-class>
            <function-signature>boolean isViewingPatientAttributeAllowed(com.example.bean.User, com.example.bean.Patient.PatientAttribute, com.example.bean.Patient)</function-signature>
            <example>
                ${ncvi:isViewingPatientAttributeAllowed(user, patientAttribute, patient)}
            </example>
    </function>Where com.example.bean.Patient.PatientAttribute is an enum (note package names have been changed to protect the innocent;-). When I try to compile my web app I get the following error:
    org.apache.jasper.JasperException: The class com.example.bean.Patient.PatientAttribute specified in the method signature in TLD for the function ncvi:isViewingPatientAttributeAllowed cannot be found. com.example.bean.Patient.PatientAttributeIf I change PatientAttribute to a static inner class of Patient, I still get the error. Are enums and inner classes allowed in function signatures?
    Thx.

    I think that you'll find it easier to define a non-inner abstract class RefBase, that exposes a removeFromQueue() method, then extend that for your Ref class. That way, the queue just deals with RefBase instances (or ? extends RefBase).
    I think that any other approach is going to get the compiler confused, because the compile-time Ref depends on the parameterization of its defining class.

  • Annonymous and inner classes

    Hello,
    Can anyone tell me what the benefits of anonymous and inner classes are? inner classes are seem pretty complicated without any obvious benefit.
    I have read about these in books and have some understanding of them but these don't appear to have any benefits.
    Any info on either would be really cool.
    regards

    There are many places where inner classes can be useful. One place where anonymous inner classes are particularly neat is for ActionListeners. For example, compare the "normal" way of doing it:
         for(int i = 0; i < 2; i++)
              JButton button = new JButton("Button " + i);
              button.setActionCommand("ACTION" + i);
              button.addActionListener(this);
         public void actionPerformed(ActionEvent e)
              if("ACTION0".equals(e.getActionCommand()))
                   doSomething(0);
              else if("ACTION1".equals(e.getActionCommand()))
                   doSomething(1);
         }with the way using anonymous inner classes:
         for(int i = 0; i < 2; i++)
              final int index = i;
              JButton button = new JButton("Button " + index);
              button.addActionListener(new ActionListener()
                        public void actionPerformed(ActionEvent e)
                             doSomething(index);
         .In the first case you need a global actionPerformed method with some if statements inside. If there are many types of action then this can quickly become very large and error-prone. In the second case, each action is handled in its own class, right with the button that it's associated with. This is easier to maintain. Note that local variables must be declared final to be accessible from the inner class.

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

  • ActionListener and Inner Class Issue

    When I add ".addActionListener()" to buttons and create an inner class to listen/handle the action, my main class does not display the GUI. If I remove the ".addActionListener()" from the buttons and the inner class, the GUI displays. Below is my code. Anyone know what is wrong with my code?
    package projects.web;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class AppletGUI{
         // JButtons
         JButton addButton = new JButton("Add");
         JButton removeButton = new JButton("Remove");
         JButton saveButton = new JButton("Save");
         JButton cancelButton = new JButton("Cancel");
         // JPanels
         JPanel containerPanel = new JPanel();
         JPanel optionsPanel = new JPanel();
         JPanel thumbnailPanel = new JPanel();
         JPanel selectionPanel = new JPanel();
         // JScrollPane
         JScrollPane thumbnailScroll;
         public AppletGUI(JRootPane topContainer){
              // Add actionListener
              addButton.addActionListener(new ButtonHandler());
              removeButton.addActionListener(new ButtonHandler());
              saveButton.addActionListener(new ButtonHandler());
              cancelButton.addActionListener(new ButtonHandler());
              // Set border layout
              containerPanel.setLayout(new BorderLayout());
              // Add buttons to target panels
              optionsPanel.add(addButton);
              optionsPanel.add(removeButton);
              selectionPanel.add(saveButton);
              selectionPanel.add(cancelButton);
              // Set size and color of thumbnail panel
              thumbnailPanel.setPreferredSize(new Dimension (600,500));
              thumbnailPanel.setBackground(Color.white);
              thumbnailPanel.setBorder(new LineBorder(Color.black));
              // Add thumbnail panel to scrollpane
              thumbnailScroll = new JScrollPane(thumbnailPanel);
              // Set background color of scrollPane
              thumbnailScroll.setBackground(Color.white);
              // Add subpanels to containerPanel
              containerPanel.add(optionsPanel, BorderLayout.NORTH);
              containerPanel.add(thumbnailScroll, BorderLayout.CENTER);
              containerPanel.add(selectionPanel, BorderLayout.SOUTH);
              // Add containerPanel to rootPane's contentPane
              topContainer.getContentPane().add(containerPanel);
         } // end constructor
         class ButtonHandler implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   new FileBrowser();
              } // end actionPerformed method
         } // end inner class ActionHandler
    } // end AppletGUI class package projects.web;
    import java.awt.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.filechooser.*;
    public class FileBrowser{
         JFileChooser fileChooser = new JFileChooser();
         public FileBrowser(){
              int fileChooserOption = fileChooser.showOpenDialog(null);
         } // end constructor
    } // end class fileBrowser

    Encephalopathic wrote:
    Dan: When it doesn't display, what happens? Do you see any error messages? Also, please take a look at your other thread in this same forum as it has relevance to our conversations in the java-forums.org about whether to add GUIs to root containers or the other way around. /PeteI fiddled with the code some more and it seems that the problem is the inner code. When I changed from the inner class to the main class implementing ActionListener and had the main class implement the actionPerformed method, the GUI displayed and JFileChooser worked as well. I've add this version of the code at the bottom of this message.
    To answer your question: When it doesn't display, what happens? -- The web page loads and is blank. And there are no error messages.
    I took a look at the other thread is this forum (the one relates to our conversation in the other forum); the problem may be the way I've add the GUI. I'll try it the other way and see what happens.
    Thanks,
    Dan
    package projects.web;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    public class AppletGUI implements ActionListener{
         // JButtons
         JButton addButton = new JButton("Add");
         JButton removeButton = new JButton("Remove");
         JButton saveButton = new JButton("Save");
         JButton cancelButton = new JButton("Cancel");
         // JPanels
         JPanel containerPanel = new JPanel();
         JPanel optionsPanel = new JPanel();
         JPanel thumbnailPanel = new JPanel();
         JPanel selectionPanel = new JPanel();
         // JScrollPane
         JScrollPane thumbnailScroll;
         public AppletGUI(JRootPane topContainer){
              // Add actionListener
              addButton.addActionListener(this);
              removeButton.addActionListener(new ButtonHandler());
              saveButton.addActionListener(new ButtonHandler());
              cancelButton.addActionListener(new ButtonHandler());
              // Set border layout
              containerPanel.setLayout(new BorderLayout());
              // Add buttons to target panels
              optionsPanel.add(addButton);
              optionsPanel.add(removeButton);
              selectionPanel.add(saveButton);
              selectionPanel.add(cancelButton);
              // Set size and color of thumbnail panel
              thumbnailPanel.setPreferredSize(new Dimension (600,500));
              thumbnailPanel.setBackground(Color.white);
              thumbnailPanel.setBorder(new LineBorder(Color.black));
              // Add thumbnail panel to scrollpane
              thumbnailScroll = new JScrollPane(thumbnailPanel);
              // Set background color of scrollPane
              thumbnailScroll.setBackground(Color.white);
              // Add subpanels to containerPanel
              containerPanel.add(optionsPanel, BorderLayout.NORTH);
              containerPanel.add(thumbnailScroll, BorderLayout.CENTER);
              containerPanel.add(selectionPanel, BorderLayout.SOUTH);
              // Add containerPanel to rootPane's contentPane
              topContainer.getContentPane().add(containerPanel);
         } // end constructor
         public void actionPerformed(ActionEvent event){
                   new FileBrowser();
              } // end actionPerformed method
         class ButtonHandler implements ActionListener{
              public void actionPerformed(ActionEvent event){
                   new FileBrowser();
              } // end actionPerformed method
         } // end inner class ActionHandler
    } // end AppletGUI class

  • Problem with Outer and Inner Classes....or better way?

    Right now I'm trying to create an Inner class.
    My .java file compiles ok, and I create my jar file too.
    But when I try to instantiate the Inner class, it fails:
    java.lang.NoClassDefFoundError: com/myco/vlXML/vlXML$vlDocument.
    Here's the class code:
    public class vlXML{
        private ArrayList myDocList=new ArrayList(); //holds documents
        public vlXML(){
        private class vlDocument{
            public vlDocument(){
            //stuff goes here
        public vlDocument vlDOC(){
            return new vlDocument();
        public void addDocument(){
            vlXML xxx=new vlXML();
            vlDocument myDoc=xxx.vlDOC();
            myDocList.add(myDoc);
        public int getNumDocs(){
            return myDocList.size();
    }Then, from a jsp page, I call:
    vlXML junk1=new vlXML();
    junk1.addDocument();...and get the error...
    Can someone help me figure out why it's failing?
    Thanks....

    You nailed it - thanks....(duh!)
    While I have your attention, if you don't mind, I have another question.
    I'm creating a Class (outer) that allows my users to write a specific XML file (according to my own schema).
    Within the XML file, they can have multiple instances of certain tags, like "Document". "Document"s can have multiple fields.
    Since I don't know how many "Documents" they may want, I was planning on using an Inner Class of "Document", and then simply letting them "add" as many as necessary (thus the original code posted here).
    Does that seem like an efficient (logical/reasonable) methodology,
    or is there there something better?
    Thanks Again...

  • Problem with final variables and inner classes (JDK1.1.8)

    When using JDK1.1.8, I came up with following:
    public class Outer
        protected final int i;
        protected Inner inner = null;
        public Outer(int value)
            i = value;
            inner = new Inner();
            inner.foo();
        protected class Inner
            public void foo()
                System.out.println(i);
    }causing this:
    Outer.java:6: Blank final variable 'i' may not have been initialized. It must be assigned a value in an initializer, or in every constructor.
    public Outer(int value)
    ^
    1 error
    With JDK 1.3 this works just fine, as it does with 1.1.8 if
    1) I don't use inner class, or
    2) I assign the value in initializer, or
    3) I leave the keyword final away.
    and none of these is actually an option for me, neither using a newer JDK, if only there is another way to solve this.
    Reasons why I am trying to do this:
    1) I can't use a newer JDK
    2) I want to be able to assign the variables value in constructor
    3) I want to prevent anyone (including myself ;)) from changing the value in other parts of the class (yes, the code above is just to give you the idea, not the whole code)
    4) I must be able to use inner classes
    So, does anyone have a suggestion how to solve this problem of mine? Or can someone say that this is a JDK 1.1.8 feature, and that I just have to live with it? In that case, sticking to solution 3 is probably the best alternative here, at least for me (and hope that no-one will change the variables value). Or is it crappy planning..?

    You cannot use a final field if you do not
    initialize it at the time of declaration. So yes,
    your design is invalid.Sorry if I am being a bit too stubborn or something. :) I am just honestly a bit puzzled, since... If I cannot use a final field in an aforementioned situation, why does following work? (JDK 1.3.1 on Linux)
    public class Outer {
            protected final String str;
            public Outer(String paramStr) {
                    str = paramStr;
                    Inner in = new Inner();
                    in.foo();
            public void foo() {
                    System.out.println("Outer.foo(): " + str);
            public static void main( String args[] ) {
                    String param = new String("This is test.");
                    Outer outer = new Outer(param);
                    outer.foo();
            protected class Inner {
                    public void foo() {
                            System.out.println("Inner.foo(): " + str);
    } producing the following:
    [1:39] % javac Outer.java
    [1:39] % java Outer
    Inner.foo(): This is test.
    Outer.foo(): This is test.
    Is this then an "undocumented feature", working even though it shouldn't work?
    However, I assume you could
    get by with eliminating the final field and simply
    passing the value directly to the Inner class's
    constructor. if not, you'll have to rethink larger
    aspects of your design.I guess this is the way it must be done.
    Jussi

  • Interface and Inner Class

    Hi,
    In interface we can't provide method body.
    but we can provide method body like this,
    public interface TestInterface {
         public class Add {
              public int add() {
                   return 100;
    what is the logic behind Inner Class inside interface.
    plz help.Thanks in advance.

    there isn't really any logic to it, it's just something that's semantically possible. there wasn't a conscious decision to allow this, it's just a by-product of the enclosing types mechanism, and while it wouldn't be a good idea to do this, there's no technical reason why it shouldn't be possible, either

  • Generics and inner classes?

    How can I say my inner class uses the same type as it's genericised host class?
    Should I just not declare a "generic" type in the inner class?
    The code
    public class LinkedList<E> implements java.util.List<E>
      ... code omitted for brevity ...
       * An internal implementation of java.util.Iterator.
      private class Iterator<E> implements java.util.Iterator<E> {
        protected Node<E> current;
        public Iterator() {
          this.current = head; // error here
      ... code omitted for brevity ...
    produces the compiler error
    C:\Java\home\src\linkedlist\LinkedList.java:59: incompatible types
    found   : linkedlist.LinkedList.Node<E>
    required: linkedlist.LinkedList.Node<E>
          this.current = head;
                         ^I understand the meaning of the compiler error... it's effectively saying that "E" is not the same type within in the Iterator class as it is in the parent LinkedList class... What I don't understand is how to make E the same type within the Iterator... if I just leave the <E> off of Iterator<E> then it throws "unchecked operation" warnings... do I just have to put up with these warnings... but no that can't be right because java.util.LinkedList has an iterator and it's not throwing unchecked operation compiler warnings... so there has to be a way...
    Thanx all. Keith.

    One more dumbshit question...
    Is there a way to do this without the warnings OR the @SuppressWarnings({"unchecked"})
       * Returns the index of the last occurrence of the specified element in this
       * list, or -1 if this list does not contain the element.
      //@SuppressWarnings({"unchecked"})
      public int lastIndexOf(Object object) {
        int i = 0;
        int last = -1;
        for(Node<E> node=this.head.next; node!=null; node=node.next) {
          if (node.item.equals((E) object)) {
            last = i;
          i++;
        return(last);
    produces the warning
    C:\Java\home\src\linkedlist\LinkedList.java:313: warning: [unchecked] unchecked cast
    found   : java.lang.Object
    required: E
          if (node.item.equals((E) object)) {
                                   ^... remembering that List specifies +public int lastIndexOf(Object object);+ as taking a raw Object, not E element, as I would have expected.
    Thanx all. Keith.

  • Javadoc and inner classes

    So, I have an inner class that has some simple setter methods. The class is declared:
    private class ClassName...and the setter, like this:
             * sets the comment string
             * @param comment, the comment to assign
            public void setComment(String comment) {
                this.comment = comment;
            }and now I'm getting lots of warnings that look like this:
    warning - @param argument "comment," is not a parameter name.We are already using "private=true" in the build.xml
    Suggestions?
    Thanks,
    Glenn

    Remove the comma and it should work.

  • Nested and inner classes

    What's the difference between them? As far as i can tell, a nested class is usually public and a inner class is almost always private. Can some one please provide an example?
    Thanks a lot guys.

    inner classes == nested classes - static classes
    In other words, inner class should belongs to the instance of the enclosing class.

  • Preverify and inner classes

    Hi. I'm trying to use a makefile to reduce build time for my project. The way it works:
    1. compile all the altered .java files
    2. preverify all of the replaced/new .class files from step 1 -- each individual file by file.
    However, I've run into a serious stumbling block. Some of my .java files contain inner classes. Step 2 works perfectly on all of the main .class files. But it simply skips the inner class .class files. I tried it manually and it had the same effect.
    Here is the command line (altered for confidentiality, but effectively the same).
    preverify -classpath "h:\\j2mewtk\\lib\\midpapi.zip;blahtmp" -d blahclasses foo.bar.baz.Foodle$FoodleFun
    This does not produce the desired output in blahclasses--it produces nothing! I'd really appreciate it if someone could tell me what to do. Is it ignoring everything after the $ sign?
    --Impulse.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    OK, well, I solved it myself. Turns out that I needed to get my makefile to replace every '$' with '\$', and then it worked perfectly.
    So I'm giving all my Duke Dollars to myself grin
    --Impulse.                                                                                                                                                                                                                                                                                                                                                                                                               

  • Menu's and Inner classes

    I am currently writing my own Chess game in Java and not very well. I want to add a 'New' section to a drop down list which sets the board back to the starting positon. But to do this I need to call a method of a class created in the outer class in the Inner class to set the array that the board is based upon to the default. Is this possible.
    If anyone could help I would be very greatful.
    Kindest Regards Deniz Tanay

    "I need to call a method of a class created in the outer class in the Inner class..."
    This doesn't make sense to me. A "class created in the outer class"? Usually the compiler creates classes. What do you mean by this phrase?
    If you wanted to call a method of the outer class, that would be easier to explain.

  • State pattern and inner classes

    Hi,
    I'm implementing the standard state design pattern. I have an object and that object delegates certain operations to various state classes. My problem is the state classes may need private information of the context class. So I can think of a few designs:
    * make the private info of the context class default so the state classes can access them
    * make appropriate getters for the private info (so again the state classes can access them
    * pass the private info to the state classes
    * make the state classes inner classes so the state classes have access to private info with any change
    I would think the inner class solution is best. any comments? thanks.

    I prefer inner classes for state objects.
    But if they become very big, maintenance can be an issue and other approaches can be more appropriate.
    JCG

Maybe you are looking for