Anonymous (unnamed) Classes by default always folllows Overriding concept

hi all,
my question is related to anonymous (unnamed) classes.
Anonymous classes are always sub-class of the some "new ClassName()". so my question is that if it is always sub-class of some class and if it is define the method that is already defined in super class then it is overriding the method. or we can say that it is by default follow the overriding principle.
I need your thoughts on this Topic.
Example Attached from SCJP Kathy Siera Book.
class Popcorn {
public void pop() {
System.out.println("popcorn");
class Food {
Popcorn p = new Popcorn() {
public void pop() {
System.out.println("anonymous popcorn");
The Popcorn reference variable refers not to an instance of Popcorn, but to an
instance of an anonymous (unnamed) subclass of Popcorn.
Let's look at just the anonymous class code:
2. Popcorn p = new Popcorn() {
3. public void pop() {
4. System.out.println("anonymous popcorn");
5. }
6. };
Regards,
Mahendra Athneria
Mumbai- India

MahendraAthneria wrote:
you want to say that use of Anonymous classes is more on to implement interface rather than extending classes?In my experience, yes. Anonymous class instances are often used as "delegates", particularly listeners plugged into some other object to allow the class to respond to events from that object. Listeners are usually defined as interfaces (although, if there are multiple event methods, there's often an "adapter" class for those who don't wish to implement all the methods).
>
one more question related to this -
yesterday i tried one program which implementing an interface. in implementer class i used @override annotation. when i compiled the program then it gives error
When you define a method declared in an interface, or as an abstract method, you are implementing the method, not overriding it.
There's no inherited method body to override.

Similar Messages

  • Trying to use super class's methods from an anonymous inner class

    Hi all,
    I have one class with some methods, and a second class which inherits from the first. The second class contains a method which starts up a thread, which is an anonymous inner class. Inside this inner class, I want to call a method from my first class. How can I do this?
    If I just call the method, it will use the second class's version of the method. However, if I use "super," it will try to find that method in the Thread class (it's own super class) and complain.
    Any suggestions?
    Code:
    public class TopClass
         public void doSomething(){
              // do something
    =============================
    public class LowerClass extends TopClass
         // overrides TopClass's doSomething.
         public void doSomething(){
              // do something
         public void testThread(){
              Thread t = new Thread(){
                   public void run(){
                        doSomething();               //fine
                        super.doSomething();          //WRONG: searches class Thread for doSomething...
              t.start();
    }

    Classes frequently call the un-overridden versions of methods from their superclasses. That's that the super keyword is for, if I'm not mistaken.You're not mistaken about the keyword, but you're not calling the superclass method from a subclass. Your anonymous inner class is not a subtype of TopLevel. It's a subtype of Thread.
    Here it is no different, except that I happen to be in a thread at the time.It's vastly different, since you're attempting to call the method from an unrelated class; i.e., Thread.
    I could also be in a button's action listener, for example. It seems natural to me that if I can do it in a method, I should be able to do it within an anonymous inner class which is inside a method.If you were in an button's action listener and needed to call a superclass' implementation of a method overridden in the button, I'd have the same questions about your design. It seems smelly to me.
    ~

  • Access Class in Default Package

    Make long story short, I have to have some class in the "(default package)", related to JNI, and I will need to pass data back and forth from and to these classes from some packaged classes. I am using Java 1.4. As I know since Java 1.4, it's not possible to access classes in default package from packaged classes directly. Is there a work around? please help...

    I DON'T have the C/C++ codeSo you have to do with the "old" classes in the default package.
    Then use jschell's suggestion to devise proxying code that allow bridging between the packages.
    since Java 1.4, I can't call the java class in the default package from packaged class any moreIf I understand jschell's post, this restriction is enforced by the Java compiler , not by the Java interpreter (JVM). Indeed this is specified in the JLS (Java Language Specifications, http://java.sun.com/docs/books/jls/third_edition/html/packages.html#7.5), not the JVM specifications (I have not verified that latter point).
    So if you get an older JDK (before 1.4 they would accept the construct), you can try writing proxy classes within a named package, proxying to the old classes in the unnamed package. Once they are compiled, and jarred together for convenience, you can switch back to the current compiler (let's says 1.6) to compile the rest of your application classes, which only use the classes in the named package, using the jar as a library.
    When executing the program, the JVM will execute everything without complaining, since it supports execution of compiled code that has been compiled with former versions.

  • Implemenet/Extend interface/class in default package

    Filename: DeaultInterface.java
    public interface DefaultInterface {
        // Abstract Methods...
    Filename: ConcreteClass.java
    package com.company;
    import DefaultInterface;
    public class ConcreteClass implements DefaultInterface {
        // Implementation of Abstract Methods...
    }When I compile above java code it gives error "cannot find symbol. symbol: class DefaultInterface".
    Can anyone explain why can't we implement the interface/extend the class in default package(no package)?
    Edited by: 974531 on Dec 2, 2012 11:07 PM

    >
    When I compile above java code it gives error "cannot find symbol. symbol: class DefaultInterface".
    Can anyone explain why can't we implement the interface/extend the class in default package(no package)?
    >
    You CAN implement the interface defined in the default package.
    What you CANNOT do is import it. And that is because the Java Language Specification specifies that named types can only be referenced by their simple name if they are imported and must otherwise be referenced by their fully qualified name.
    See the 7.5 Import Declarations in the Java Language Specification - http://docs.oracle.com/javase/specs/jls/se7/html/jls-7.html
    >
    An import declaration allows a named type or a static member to be referred to by a simple name (§6.2) that consists of a single identifier.
    Without the use of an appropriate import declaration, the only way to refer to a type declared in another package, or a static member of another type, is to use a fully qualified name (§6.7).
    A type in an unnamed package (§7.4.2) has no canonical name, so the requirement for a canonical name in every kind of import declaration implies that (a) types in an unnamed package cannot be imported, and (b) static members of types in an unnamed package cannot be imported. As such, §7.5.1, §7.5.2, §7.5.3, and §7.5.4 all require a compile-time error on any attempt to import a type (or static member thereof) in an unnamed package.
    >
    So you can't reference that type by importing it because you can't import a type that doesn't have a canonical nmae. And you can't just use the simple name because, as the first statement above says you have to import it to use the simple name.
    When you use the simple name of that type without an import the simple name would refer to a class IN your 'com.company' named package.

  • Mysterious anonymous inner class in switch block

    public class MysteryFile {
      public enum Elements {
        WIND, EARTH, FIRE, WATER
      Elements el;
      public MysteryFile(Elements el) {
        this.el = el;
      public void whatIsItLike() {
        switch (el) {
          case WIND: System.out.println("A bit chilly sometimes"); break;
          case EARTH: System.out.println("Gets hands dirty."); break;
          case FIRE: System.out.println("Hot! skin melt"); break;
          case WATER: System.out.println("Cool! clean hands"); break;
          default: System.out.println("Don't know"); break;
      public static void main(String[] args) {
        MysteryFile anElement = new MysteryFile(Elements.FIRE);
        anElement.whatIsItLike();
    }When compiled in Netbeans or in the command line, generates an unexpected MysteryFile$1.class file. If the entire switch block is commented out and recompiled, it does not get generated. Where does this anonymous inner class come from?

    The MysteryFile$1 class looks something like this (javac 1.6.0_02):
    class MysteryFile$1 {
      static final int[] $SwitchMap$MysteryFile$Elements;
      static {
          // the line number (debug info) of this static initializer
          // is "switch (el)" line in MysteryFile.java
          $SwitchMap$MysteryFile$Elements =
                  new int[MysteryFile$Elements.values().length ];
          try {
              $SwitchMap$MysteryFile$Elements[
                      MysteryFile$Elements.WIND.ordinal() ] = 1;
          } catch (NoSuchFieldError e) {
              // fix stack?
          // repeat with EARTH(2), FIRE(3) and WATER(4)
    }... and the actual switch statement in 'MysteryFile' looks like so:
      //switch (el) {
      switch(MysteryFile$1.$SwitchMap$MysteryFile$Elements[
              this.el.ordinal() ])
      case 1:  // WIND
          break;
      case 2:  // EARTH
          break;
      case 3:  // FIRE
          break;
      case 4:  // WATER
          break;
      default:  // ...
      }I suppose this is necessary because the compiler can't guarantee that the runtime enum-constant-to-ordinal mapping will be identical to that at compile time (the API docs say it depends on the declaration order in the source code, which I think may change without breaking binary compatibility).
    PS MysteryFile$Elements.values() is a synthetic method that returns all enumeration constants in a MysteryFile$Elements array. Found this old related thread: [http://forum.java.sun.com/thread.jspa?threadID=617315]

  • Anonymous Inner Class question

    How can I get "foof" to be echoed to the screen?
    class MyClass {
       void go() {
          Bar b = new Bar();
          b.doStuff(new Foo() {
             public void foof() {
                System.out.println("foof");
    interface Foo {
       void foof();
    class Bar {
       void doStuff(Foo f) {}
    public class TestWonder {
       public static void main (String... args) {
       new MyClass().go();
       //Why doesn't this print out "foof" to the screen? Nothing is echoed to the screen.
    }

    Sorry to be so thick, but I thought that the code did that already. Apparently it doesn't. In other words, how would the code invoke the override foof()? I should be clearer:
    I know if I change Bar's doStuff() to
    void doStuff(Foo f) {
    System.out.println("bar's dostuff");
    }then when go() is executed bar's dostuff will print out. But, what about the override in the anonymous inner class?
    Edited by: RonNYC2 on Feb 5, 2010 1:03 PM
    Edited by: RonNYC2 on Feb 5, 2010 1:05 PM

  • DynamicStream class play2 function and error overriding it

    Adobe made a "DynamicStream" class that looks pretty cool.  I'd like to use it.  The class contains the following code:
             override public function play2(param:NetStreamPlayOptions):void {
                throw new Error( "The play2() method has been disabled for this class.  Please create a separate NetStream object to use play2()." );
    The compiler complains about this function.  Says "the method marked override must override another method".  It doesn't complain about it if I instantiate class in my main application file.  That's what the sample code in the Adobe productivity tools suite does - uses the class in the main application file.
    If I use it in a custom component file though the compiler complains.
    What do I do with this function if I intend to instantiate the DynamicStream class in a custom component file?

    I too ran into this problem, if you are using the Flex SDK you must set the target flash player version to at least 10.0.0 otherwise the error occurs because play2() is not available in 9. By default the target version for all Flex 3.4 is 9.x, so you must change the target to 10. Let me know if you have anymore problems.

  • Semi-Anonymous Inner Class?

    From API description of invokeLater method of SwingUtilities class:
    /* begin quote
    In the following example the invokeLater call queues the Runnable object doHelloWorld on the event dispatching thread and then prints a message.
    Runnable doHelloWorld = new Runnable() {
    public void run() {
    System.out.println("Hello World on " + Thread.currentThread());
    SwingUtilities.invokeLater(doHelloWorld);
    System.out.println("This might well be displayed before the other message.");
    */ end quote
    The interface class is named (doHelloWorld) so it's not really anonymous.
    But the class is not declared; there's no class keyword.
    Is there a formal name for this construction?
    It seems like a hybrid of named and anonymous implementation.
    I guess the ability to mix class declaration, instantiation, method declaration, etc in one statement is powerful but just hard for beginner to understand when to use.
    Sigh, three ways to do same thing. This 'hybrid' form is actually harder to understand than other ways.
    private class myRunnable implements Runnable {
    public void run() {
    System.out.println("Hello World on " + Thread.currentThread());
    myRunnable doHelloWorld = new myRunnable();
    OR
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    System.out.println("Hello World on " + Thread.currentThread());
    Thanks,
    Stanley.

    The interface class is named (doHelloWorld) so it's
    not really anonymous. No. There's a variable that points to an instance of that class, and the variable is named doHelloWorld. The class is anonymous.
    Is there a formal name for this construction?Anonymous inner class.

  • Creating an anonymous parametrized classes

    1.Can anyone please give me a code snippet how to create an anonymous parametrized class. I tried creating one, but i am going wrong some where, can anyone correct me.
    class Child extends Parent{
              void pmethod(){
         System.out.println("This is a test method");
         class abc{
          abc(){
              System.out.println("pp " + Child.super.i);
              extendi epp = new extendi()(10){  // creating PARAMETRIZED ANONYMOUS CLASS
              public void callMe()
         abstract class extendi implements i{
              int var;
              extendi(int i){
                    var =10;
              public void callMe(){
              System.out.println("This implements inner class " + var);
    }Also
    2. What is the use of nested interfaces. Any code snippet available.

    extendi epp = new extendi()(10){  // creatingextendi epp = new extendi(10){  // creating
    eating PARAMETRIZED ANONYMOUS CLASS
         public void callMe()
         abstract class extendi implements i{
              int var;
              extendi(int i){
              var =10;
              public void callMe(){
    System.out.println("This implements inner class " +
    + var);
    Also
    2. What is the use of nested interfaces. Any code
    snippet available.

  • Question about anonymous inner class??

    Is there any error occurs,If a class declear & implement two anonymous inner classes ??

    public class TryItAndSee {
        void m() {
            Runnable x = new Runnable(){
                public void run() {
                    System.out.println("?");
            Runnable y = new Runnable(){
                public void run() {
                    System.out.println("!");
    }

  • Question on Anonymous Inner class !

    Can an Anonymous Inner class implement or extend any thing?
    I feel no .. if yes can anyone give an example please..

    An example: the anonymous inner class in u extends Thread.
    $ cat u.java
    class u {
    public static void main(String a[]) {
    Thread t = new Thread ( ) {
    public void run() {
    System.out.println(getClass().getName());
    t.start();
    $ javac u.java
    $ java u
    u$1
    $
    The same idea but with the Runnable interface (and not class)
    $ cat u.java
    class u {
    public static void main(String a[]) {
    Thread t = new Thread ( new Runnable ( ) {
    public void run() {
    System.out.println(getClass().getName());
    t.start();
    $ java u
    u$1

  • Adapters vs anonymous inner class (please help)

    I am trying to clean up my code by using anonymous inner classes to handle some action events. My code looks like this but I get an error
    Button.addActionListener(new MyClass() {
    public void actionPerformed(ActionEvent e) {
    my_Button_actionPerformed(e);
    it says that it cant find MyClass, but I thought I dont need to define it becaue I am defining it here, isnt that the point of a anonymous inner class

    yourBtn.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
    });(BTW: use code tags in posting!)

  • Cant complie "anonymous inner class" on JDK1.4

    public Enumeration enumerator()
    return new Enumeration()
    int currentItem = items.size() - 1;
    public boolean hasMoreElements() {
    return (currentItem >= 0);
    error: cant resolve symbol
    help me! thanx u very much

    Since Enumeration is an interface, the anonymous inner class needs to implement both functions.
    public Enumeration enumerator()
      return new Enumeration()
         int currentItem = items.size() - 1;
         public boolean hasMoreElements()
            return (currentItem >= 0);
         public Object nextElement()
            return items.elementAt(currentItem--);
    }I assume that items is a member field of the class containing this method. Since I don't know what it is , the elementAt is only a guess.

  • BUG: ojc compiler doesnt handle @Override on anonymous inner class methods

    Hi,
    jdev 10.1.3.3.0.4157, XP SP2, jdk 5 u13:
    for the following code sample:
    Object o = new Object()
        @Override
        public String toString2()
            return "some string";
    };With ojc set as a compiler (the default), ojc doesnt catch the error about overriding toString with toString2, changing the compiler to javac achieves the required and correct behavior.

    Thanks Frank, I logged a couple more not so serious issues a while back but didnt get any feedback on them. The subject of the posts didn't have a 'BUG' prefix though. Should I edit them so to give them some attention, or were they silently logged :) ?

  • ER: Override Methods feature should detect anonymous inner class scope

    Hi,
    Given the following code:
    public class Class1 {
        public static void main(String[] args) {
            Thread t = new Thread() {
                // line 4
            t.start();
    }When the cursor is placed on line 4, activating the Override Method dialog (Source menu), should show Thread methods that I can override, in addition to Object methods. Currently only the method from class Object are being shown. The same treatment should also apply to local method inner classes. This happens with the latest 11g preview 3, and all previous versions.

    Hi,
    I'll file an ER
    Frank

Maybe you are looking for

  • After creating a keynote, can it be converted into a powerpoint?

    after creating a keynote can I convert it to a powerpoint to show on my company systems?

  • Can you send a route or waypoints to Nokia 700 GPS...

    I was wondering if you can somehow send specific routes and/or waypoints to the Nokia GPS system on my phone.

  • Deskjet F2480 manual pring both sides

    HP Deskjet F2480, Dell Hardware, Windows 7 and windows office 2010 Home edition, hard wired to printer. Manualy printing both sides mixes up the pages. It would appear that first print odd numbered pages prints 1,2,3,4etc. then when turned and contin

  • Problems with f4fpackager for videos in H264 codec

    Hi, I have been trying to use the f4fpackager for some videos i have encoded in h264 using the following ffmpeg command: ./ffmpeg -i video.mp4 -acodec libmp3lame -ab 96k -r 25 -vcodec libx264 -fpre ./ffpresets/libx264-fast.ffpreset -b 1200000 -s 852x

  • Scripting Flash

    I have not been able to find a scripting forum for Flash, so please forgive me if this is the wrong forum... Some of you might have noticed the existance of Script Bay. It is a free panel for writing and running scripts and it works in the many of th