Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: Help with Anonymous Inner class

  1. #1
    Member
    Join Date
    May 2011
    Posts
    61
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Help with Anonymous Inner class

    Hi, I'm trying to practice with anonymous inner classes, so I written a simple Dog class, AnonymousInnerClass class that uses Dog as an anonymous inner class and the main method in class: AnonymousInnerCLassRunner, my question is why does it all compile and run but how do I get it to invoke the new_dog_method() which houses the anonymous inner class?a
    Also, I created another instance of AnonymousInnerClass, but when I recompile, I still have the one: AnonymousInnerClass$1.class, but there isn't:AnonymousInnerClass$2.class created though so it it shared?

    AnonymousInnerClass class
    import java.util.*;
     
    public class AnonymousInnerClass
    {
    	private int outer_num;
     
    	public AnonymousInnerClass(int n)
    	{
    		this.outer_num = n;
    	}
     
    	public int getOuterNum(){return this.outer_num;}
     
    	public void setOuterNum(int n){this.outer_num = n;}
     
    	public void zing()
    	{
    		final String hero = "Snoopy";
    		Dog d = new Dog("Ash Ketchum")
    		{
    			public void new_dog_method()//How do I call this in AnonymousInnerClassRunner? I thought anonymous inner class is extending my Dog class?
    			{
    				System.out.println(hero);
    				System.out.println("ABC");
    				System.out.println("123 and so forth");
    			}
    		};
     
    		System.out.println("output inside zing method but outside anonymous inner class");
    	}
     
    	public void sing()
    	{
    		System.out.println("Singin' in the rain!");
    	}
    }

    AnonymousInnerClassRunner (main method, but why doesn't program output the statements inside the new_dog_method() method?)
    import java.util.*;
     
    public class AnonymousInnerClassRunner
    {
    	public static void main(String[] args)
    	{
    		AnonymousInnerClass a = new AnonymousInnerClass(89);
    		a.zing();//this works, but it doesn't output statements inside new_dog_method()
    		// a.zing().new_dog_method()//this doesn't work...
    		a.zing();//this outputs fine
    		a.sing();//this outputs fine
     
                    AnonymousInnerClass aa = new AnonymousInnerClass(89);
    		aa.zing();//Q: why isn't AnonymousInnerClass$2.class created?
    	}	
    }

    Dog class, just a regular class
    import java.util.Random;
     
    public class Dog//I'm using this to test anonymous inner classes (assuming this class is 'useless' on its own)
    {
    	private String owner;
    	private String breed;
    	private int breed_num;
     
    	//an index b/t 0 and 8
    	private String breed_arr[] = {"weiner", "husky", "blood hound", "poodle", "golden retriever", "bull dog", "great dane", "pommeranian", "dalmation"};
     
     
    	public Dog(String o)
    	{
    		this.owner = o; 
     
    		//randomly choose a breed
    		Random r = new Random();
     
    		breed_num = r.nextInt( breed_arr.length );//size is 9 so: random val % 9 gives a value b/t [0 - 8]
     
    		this.breed = breed_arr[ breed_num ];
    	}
     
    	public int getBreedNum(){return this.breed_num;}
     
    	public void setOwner(String name){this.owner = name;}
     
    	public String getBreed(){return this.breed;}
     
    	public void bark(int breed_num)
    	{
    		switch(breed_num)
    		{
    			case 0:
    			{
    				System.out.println("wimper!");
    				break;
    			}
    			case 1:
    			{
    				System.out.println("Husk husk!");
    				break;
    			}
    			case 2:
    			{
    				System.out.println("bark bark!");
    				break;
    			}
    			case 3:
    			{
    				System.out.println("poof, poof...");
    				break;
    			}
    			case 4:
    			{
    				System.out.println("Ruff, ruff!");
    				break;
    			}
    			case 5:
    			{
    				System.out.println("GRRRRR!");
    				break;
    			}
    			case 6:
    			{
    				System.out.println("Roooof!");
    				break;
    			}
    			case 7:
    			{
    				System.out.println("brrark");
    				break;
    			}
    			case 8:
    			{
    				System.out.println("Woof, woof!");
    				break;
    			}
    			default:
    			{
    				System.out.println("bark!");
    				break;
    			}
    		}
     
    	}
    }


  2. #2
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: Help with Anonymous Inner class

    but how do I get it to invoke the new_dog_method()
    You can't.

    There is nothing to stop an anonymous class extending a "normal" class - like your anonymous class extends Dog - and the anonymous can create some more methods. But, to call those methods (from outside the anonymous class itself) you would have to declare a variable whose type was the anonymous class. And you can't do that because ... the anonymous class doesn't have a name!

    Typical usage of anonymous classes is where they extend (/implement) an abstract class (/interface) or a class with very little functionality. What they do is add the implementation of methods that have already been declared by the class (/interface) they are extending (/implementing). They are typically also very brief otherwise the logic gets quite tangled, quite quickly.

    ---

    Your AnonymousInnerClass has an odd name, in as much as it *isn't* an anonymous inner class: it has a name, so it's not anonymous.

  3. #3
    Member
    Join Date
    May 2011
    Posts
    61
    My Mood
    Busy
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Help with Anonymous Inner class

    Actually I wanted the Dog class to be the anonymous inner class, I think that's what you meant and I understand the poorly named class of: AnonymousInnerClass. So if use of anonymous inner is to extend functionality or honor a contract if implementing an interface (so to define all methods), what's the point of using anonymous inner classes if the overridden methods or implemented methods of an interface can't be invoked?

    I found online that they come in handy w/ event-driven programming so Swing for example where it saves time from typing to register a listener as in;
    button.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e)
        {
            // do something.
        }
    });
    and with this button registered as a listener, it is implementing the ActionListener interface (which has only one method to implement as part of contract when implementing any interface (unless you use adapters, another story) ), but actionPerformed is not invoked manually by the user, me, but done automatically whenever this button is clicked. But my Dog class is user-defined and so I can't call the new_dog_method() so just curious

  4. #4
    Super Moderator pbrockway2's Avatar
    Join Date
    Jan 2012
    Posts
    987
    Thanks
    6
    Thanked 206 Times in 182 Posts

    Default Re: Help with Anonymous Inner class

    Actually I wanted the Dog class to be the anonymous inner class,
    Just a nitpick, but you want some *subclass* of' Dog to be an anonymous class. I just want to emphasise the point that anonymous classes have no name, so you can never (reasonably) say "I want Whatever to be an anonymous class".

    ---

    ActionListener is a good - and typical - example. Which answers your question about "what's the point of using anonymous inner classes". They are used when they implement some behaviour described in the parent and where it makes sense to put the implementation close to some other object. (the way the listener implementation is close to the button instantiation.)

    In fact you *can* call the actionPerformed() method if you really want to. All that's needed is that you have a variable with which to call it:

    ActionListener listener = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            // stuff happens here
        }
    } // listener is an instance of an anonymous subclass of ActionListener
    button.addActionListener(listener);
        // the following is quite "legal"
    listener.actionPerformed(null);

    Of course null is not a "proper" argument, but so long as nothing depends on getting a "real" ActionEvent there will be no problems. In any event it compiles OK, so methods of anonymous subclasses can be called.

    Note that actionPerformed() is declared in the (non-anonymous) ActionListener class. The problem arises only when you want to call some method that is *not* declared in the nonanonymous parent. The compiler - as always - insists that the variable (or other expression) has a type where this new method is declared. But you can't declare such a variable because the class in question has no name. And you can't cast an expression of the parent type to the anonymous subtype either, for the same reason.

    The bottom line is that if you want a class which declares some method you intend calling later you had better give that class a name:

        // untested - access modifiers removed since the example involves a *local* class
    public void zing()
    {
        final String hero = "Snoopy";
        class DogEx extends Dog
        {
            DogEx(String name)
            {
                super(name)
            }
     
            void new_dog_method()
            {
                System.out.println(hero);
                System.out.println("ABC");
                System.out.println("123 and so forth");
            }
        };
        DogEx d = new DogEx("Ash Ketchum");
        d.new_dog_method();
     
        System.out.println("output inside zing method but outside anonymous inner class");
    }

    You ought to have a reason for complexifying the code in this way. Ie some reason not to define DogEx in its own file.
    Last edited by pbrockway2; January 4th, 2013 at 01:10 AM. Reason: added new_dog_method() call

Similar Threads

  1. Replies: 2
    Last Post: November 18th, 2012, 02:09 PM
  2. need to make basic class and implementation class (base class without void main)
    By javanewbie101 in forum Object Oriented Programming
    Replies: 1
    Last Post: September 19th, 2012, 08:03 PM
  3. Anonymous class Example : What's wrong with my code?? :(
    By JavaEnthusiast in forum What's Wrong With My Code?
    Replies: 3
    Last Post: August 2nd, 2012, 03:25 PM
  4. Replies: 3
    Last Post: June 17th, 2012, 06:22 PM
  5. Anonymous is here
    By anonymous in forum Member Introductions
    Replies: 2
    Last Post: March 1st, 2010, 03:10 AM