JLS3: Scope of type parameter and inner class declaration

The following code:
class Foo<E>
  class E
    E foo()
      return this;
}produces this error message:
$ javac Foo.java
Foo.java:7: incompatible types
found   : Foo<E>.E
required: E
      return this;
             ^
1 errorApparently, the type parameter E of the outer class Foo shadows the inner class declaration E. An alternative way to check is to create a new E() in this method, which results in an error message about using a type parameter where a type is expected.
Of course this code is sick, but I would like to know where this is defined in the JLS3, since I cannot find out in which way this shadowing works. What I've found until now:
Page 179:
"The scope of a class' type parameter is the entire declaration of the class."
Page 190:
"The scope of a declaration of a member m declared in or inherited by a class type C is the entire body of C, ... "
Page 132:
"If a type name consists of a single Identifier, then the identifier must occur in the scope of exactly one visible declaration of type with this name, or a compile time error occurs."
Section 6.3.1 (Shadowing declarations) specifies the shadowing rules, but does not mention type parameters.
Any help is appreciated.

The current behaviour in eclilpse seems to be the one we get if the bug in javac is fixed as described.
This code compiles
public class Shadow1 {
     class Foo<E>
       class E
          E foo()
           return this;
}but this code
        Foo<E>.E foo()
           return this;
         }shows
Type mismatch: cannot convert from Shadow1.Foo<E>.E to Shadow1.Foo<Shadow1.Foo<E>.E>. E
Not sure if this error message is correct.

Similar Messages

  • Hw To Make Inner Class Distinguish Func Parameter And Outer Class Var

    i fail to make an inner class distinguish among function parameter and outer class variable.
    consider the following code:
    public class a {
         int var; // i want to access this one using inner class.
         public a(int var) {
              this.var = var;
              class b {
                   public void fun() {
                        var = 100;
    i get an error a.java:9: local variable var is accessed from within inner class; needs to be declared final.
    when i change the code to this:
    public class a {
         int var; // i want to access this one using inner class.
         public a() {          
              class b {
                   public void fun() {
                        var = 100;
    it compiled no problem.it seems that inner class is accessing function parameter rather than outer class member.
    is there any syntax i can use to make me access the outer class member variable whithout renaming or removing the function parameter?
    thank you.

    a.this.var = 100; //Use this in the inner class.Amazing syntax -:)

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

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

  • Clear definition+examples- type variable, type parameter and type argument

    I am trying to fully understand the terms like type variable, type parameter and type argument as they apply to generics. Can anyone please give the exact definition and example of each of these terms. Also how these terms relate to the classes/interfaces in language model APIs of Java 6.

    http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html

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

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

  • 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

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

  • 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

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

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

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

Maybe you are looking for