Results 1 to 16 of 16
  1. #1
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    3

    Default Does an anonymous class have to extend a class or implement an interface ?

    Does an anonymous class have to extend a class or implement an interface ?

    If it does not, then what would it return ?

    If yes,
    then does it only depend on the return type ?

    If I have an interface MyInterfacein myPackage1,
    and if I have a class MyClass in myPackage2, can I simply say:

    Java Code:
    new MyInterface()
    {
     //Something something something..
    };
    and expect a new Object of an annymonms class that is referenced by MyInterface?
    Last edited by fatabass; 02-04-2012 at 09:03 PM. Reason: forgot the () in the Code

  2. #2
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,058
    Rep Power
    6

    Default Re: Does an anonymous class have to extend a class or implement an interface ?

    Every class has to extend a class or implement an interface. Classes that don't explicitly do this implicitly extend Object.

    Classes don't "return" anything; their methods do.

    You'd have to import MyInterface to use it in myPackage2, but otherwise yes.
    Get in the habit of using standard Java naming conventions!

  3. #3
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Does an anonymous class have to extend a class or implement an interface ?

    Quote Originally Posted by fatabass View Post
    Does an anonymous class have to extend a class or implement an interface ?
    Yes, at the very least it must extend Object:
    Java Code:
          Object myFoo = new Object() {
             @Override
             public String toString() {
                return "my Foo!";
             }
          };
          
          System.out.println(myFoo);
    If it does not, then what would it return ?
    Question is meaningless since it does have to extend something.

    If yes,
    then does it only depend on the return type ?
    Makes no sense. return type of what?


    If I have an interface MyInterfacein myPackage1,
    and if I have a class MyClass in myPackage2, can I simply say:

    Java Code:
    new MyInterface()
    {
     //Something something something..
    };
    and expect a new Object of an annymonms class that is referenced by MyInterface?
    Best to try it and see what happens!

  4. #4
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    3

    Default Re: Does an anonymous class have to extend a class or implement an interface ?

    Thanks. I was thinking for something like this:

    Java Code:
    package myPackage;
    
    public class Parcel8 
    {
    	public Wrapping wrapping(int x)
    	{
    		return new Wrapping(x) 
    		{};
    		
    	}
    }
    ( I have a class called Wrapping in the same package. )

    So I have an anonymous class here, that I know. But why am I not just creating a Wrapping object ?

    Java Code:
    package myPackage;
    
    public class Wrapping 
    {
    	private int i;
    	
    	public Wrapping (int x)
    	{
    		i=x;
    	}
    	
    	public int value()
    	{
    		return i;
    	}
    	
    }
    ( This example is from Thinking in JAVA. This is a very good book, but all the examples are just so very "meaningless." Difficult to understand "why". )

  5. #5
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Does an anonymous class have to extend a class or implement an interface ?

    Quote Originally Posted by fatabass View Post
    Thanks. I was thinking for something like this:
    So I have an anonymous class here, that I know. But why am I not just creating a Wrapping object ?
    Why indeed. That's just what you're doing. I don't see why you have the empty {} if you're not using them to overload a method or two.

  6. #6
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    3

    Default Re: Does an anonymous class have to extend a class or implement an interface ?

    ( I actually meant why is there an example like this ? I am just following the example )

    So what I am doing here is:

    Creating an object from a nameless class that is referenced by type Wrapper..

    And I would want to do that because:
    I may want to override some methods ?
    Overload some methods ?
    Add some new methods in the nameless class ?

    But if I overload some methods, how can I call the methods using my Wrapper reference ? The Wrapper class will not have the new methods ?

  7. #7
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Does an anonymous class have to extend a class or implement an interface ?

    Quote Originally Posted by fatabass View Post
    Does an anonymous class have to extend a class or implement an interface ?
    Yes. But notice why. All classes extend Object, and anonymous ones are no exception.

    If it does not, then what would it return ?

    If yes,
    then does it only depend on the return type ?
    I'm not sure I understand this. What is "it" - the class being extended? The return type of what? Only methods have return types, and you haven't mentioned any methods.

    The class being extended will be whatever class you say is being extended when you use the "new" operator.

    Java Code:
        // MouseAdapter is being extended.  Ie the anonymous class is a direct
        // subclass of MouseAdapter
    MouseAdapter ma = new MouseAdapter() {
        // etc
    }; 
    
        // Object is being extended.  Ie the anonymous class is a direct
        // subclass of Object
    ActionListener al = new ActionListener() {
        //etc
    };
    (See JLS15.9.1 Determining the Class being Instantiated.)

    If I have an interface MyInterfacein myPackage1,
    and if I have a class MyClass in myPackage2, can I simply say:

    Java Code:
    new MyInterface()
    {
     //Something something something..
    };
    and expect a new Object of an annymonms class that is referenced by MyInterface?
    Notice that the expression "new MyInterface(){/*etc*/}" does nothing useful. It instantiates an instance of an anonymous class that is a direct subclass of Object (as explained above), but you don't do anything *with* that reference. Typical things you might do with it are assign it to something, or call its methods.

    Java Code:
    public class UsingAnonEg {
        public static void main(String[] args) {
                // call its method
            new Foo() {
                public void foo() {
                    System.out.println("foo called");
                }
            }.foo();
            
                // or assign it to something
            Foo reallyReallyFoo = new Foo() {
                public void foo() {
                    System.out.println("foo called!!!");
                }
            };
            reallyReallyFoo.foo();
        }
    }
    
    // possibly declared elsewhere
    
    interface Foo {
        void foo();
    }

  8. #8
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    25

    Default Re: Does an anonymous class have to extend a class or implement an interface ?

    Quote Originally Posted by fatabass View Post
    But if I overload some methods, how can I call the methods using my Wrapper reference ? The Wrapper class will not have the new methods ?
    Sorry, I meant override methods. Those you'll be able to call since their signature is part of the parent class.

  9. #9
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    3

    Default Re: Does an anonymous class have to extend a class or implement an interface ?

    Thanks both pbrockway2 and Fubarable.

  10. #10
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Does an anonymous class have to extend a class or implement an interface ?

    But if I overload some methods, how can I call the methods using my Wrapper reference ?
    If you have a variable (or expression) of type Wrapper you *can't* call methods declared in some other type without casting. And you can't cast if that other type is anonymous.

    Overriding is OK. The variable can be declared as type Wrapper then when you invoke the method what gets called is the overridden form of the anonymous subclass.

    Java Code:
    
    public class Asd {
        
        public static void main(String[] args) {
            Foo test = new Foo() {
                void foo(int i) {
                    System.out.println("overridden foo called");
                }
                    // we can't call this one ... *because* the runtime type of
                    // test has no name.
                void foo(long j) {
                    System.out.println("overloaded foo called");
                }
            };
            test.foo(1);
            /*
            ((???)test).foo(1L);
            */
            
            test = new Bar();
            test.foo(1);
            ((Bar)test).foo(1L);
        }
    }
    
    class Bar extends Foo {
        void foo(int i) {
            System.out.println("Bar's overridden foo called");
        }
    
        void foo(long j) {
            System.out.println("Bar's overloaded foo called");
        }
    }
    
    // possibly declared elsewhere
    
    class Foo {
        void foo(int i) {
            System.out.println("plain foo called");
        }
    }

  11. #11
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    3

    Default Re: Does an anonymous class have to extend a class or implement an interface ?

    Thanks for the great explanation.

  12. #12
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Does an anonymous class have to extend a class or implement an interface ?

    You're welcome.

    Overridden methods are in the same boat as any other methods you might add when anonymously extending a class or implementing an interface. Not being able to call them is a *feature* not a problem. Suppose I have implemented a data structure like a tree or something and people using it want to have an iterator. I can return them an instance of an anonymous class that implements Iterator. This anonymous class can have helper methods that use the "secret" stuff that is part the implementation of my tree and I can be quite sure that the user of the iterator will never be able to call those methods directly because they can never cast the iterator to the right type.

  13. #13
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    3

    Default Re: Does an anonymous class have to extend a class or implement an interface ?

    Thanks, what is confusing me more is

    An InnerClass has to be defined 'from' some other class or interface I suppose ?

    Like saying:

    Java Code:
    new ActionListener()
    {
    //Override some methods here.. This is now an Inner-class implementing ActionListener because I started saying new ActionListener()...
    };
    I have a class here that has no name, but it is implementing ActionListener.

    Is there anyway ( and/or reason) to do something like

    Java Code:
    {
    //This is a crazy inner class with some methods and variables, but I have no idea how to declare this class and use it.
    };
    So my question is:
    Is an Inner-Class always declared by a preciding Interface or an Existing Class, like:
    Java Code:
    SomeClass()
    {
    An inner-class that is extending SomeClass automatically? 
    };

  14. #14
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Does an anonymous class have to extend a class or implement an interface ?

    Is an Inner-Class always declared by a preciding Interface or an Existing Class
    Yes, always.

    The section of the JLS I linked to earlier is straight forward about this. You get new instances with a so called "class instance creation expression" and these always involve a class or interface type. They may optionally have a class body and that's when you get an anonymous class.

    and/or reason
    I'll be controversial and say that, yes, there is plenty of reason why you might want to do this. You know what you want your class to do (its methods) and that's all: you have no wish to lock it down into a particular framework of classes by specifying that it is a direct subclass of something else.

    But you are not going to be able to express that intent in Java. Java is strongly typed: other people's methods will specify what types they expect as arguments, and your variables will be declared in such a way that at least the direct parent class and interfaces are known. You can call the other person's method with your reference value only if there is a "match" between the other person's expectations and your declarations.

    For an alternative approach see http://en.wikipedia.org/wiki/Duck_typing

  15. #15
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    3

    Default Re: Does an anonymous class have to extend a class or implement an interface ?

    Thanks pbrockway2, you rock.. :)

  16. #16
    fatabass is offline Senior Member
    Join Date
    Nov 2011
    Location
    Turkey
    Posts
    380
    Blog Entries
    24
    Rep Power
    3

    Default Re: Does an anonymous class have to extend a class or implement an interface ?

    To everyone that may read this thread, I have also found this very short but clear article:

    Java Tutorial Online: Anonymous Inner Class in Java

    This is from that article:

    The key to understand this is that, actually the Anonymous inner class always extend or implement, but not both at the same time.

Similar Threads

  1. Issue in method anonymous class in GWT
    By ankit01 in forum GWT
    Replies: 0
    Last Post: 05-16-2011, 11:25 AM
  2. Replies: 2
    Last Post: 05-01-2010, 08:59 AM
  3. Trying to extend class
    By ribbs2521 in forum New To Java
    Replies: 4
    Last Post: 10-29-2009, 06:28 PM
  4. Name of Anonymous class
    By eva in forum New To Java
    Replies: 1
    Last Post: 12-31-2007, 01:07 PM
  5. Anonymous class
    By ravian in forum Advanced Java
    Replies: 3
    Last Post: 12-25-2007, 10:56 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •