Why a static class can implements a non-static interface?

public class Test {
     interface II {
          public void foo();
     static class Impl implements II {
          public void foo() {
               System.out.println("foo");
}Why a static class can implements a non-static interface?
In my mind, static members cann't "use" non-static members.

Why a static class can implements a
non-static interface?There's no such thing as a non-static member interface. They are always static even if you don't declare them as such.
An interface defines, well, a public interface to be implemented. It doesn't matter whether it is implemented by a static nested class or by an inner class (or by any class at all). It wouldn't make sense to enforce that it should be one or the other, since the difference between a static and non-static class is surely an irrelevant detail to the client code of the interface.
In my mind, static members cann't "use" non-static
members.
http://java.sun.com/docs/books/jls/third_edition/html/classes.html#246026
Member interfaces are always implicitly static. It is permitted but not required for the declaration of a member interface to explicitly list the static modifier.

Similar Messages

  • Why a non static member class can be defined in an interface

    Non-static member classes are defined as instance members of other classes, just like fields and instance methods are defined in a class. An instance of a non-static member class always has an enclosing instance associated with it.
    An interface can't be instantiated then how a non static member class will have an enclosing instance associated with it.
    interface outer
            public  class inner{
            public void p()
                System.out.println("inside interface's non static member class");
        public  static class inner1{
                public void p(){System.out.println("inside interface's  static member class");
    public class Client {                                           // (11)
        public static void main(String[] args) {                    // (12)
        outer.inner nonStatic = new outer.inner();
            nonStatic.p();
        outer.inner1 stat = new outer.inner1();
          stat.p();
    }inner is a non static member class even then " outer.inner nonStatic = new outer.inner();" working fine ?????????????

    class outer
            public  class inner{
            public void p()
                System.out.println("inside interface's non static member class");
    public class Client {                                           // (11)
        public static void main(String[] args) {                    // (12)
        outer.inner nonStatic = new outer.inner();
        nonStatic.p();
    }on compiling the above code the error message i got is
    "not an enclosing class: outer"
    the reason of this compilation error is "outer.inner nonStatic = new outer.inner();
    it should be "outer.inner nonStatic = new outer(). new inner();"
    now my question is
    interface outer
            public  class inner{
            public void p()
                System.out.println("inside interface's non static member class");
    public class Client {                                           // (11)
        public static void main(String[] args) {                    // (12)
        outer.inner nonStatic = new outer.inner();
        nonStatic.p();
    }on compiling the above code why compilation error is not coming??????????
    i think now it is more clear what i am asking

  • Why a nested class can instantiate an abstract class?

    Hi people!
    I'm studying for a SCJP 6, and i encountered this question that i can figure it out but i don't find any official information of my guess.
    I have the following code:
    public class W7TESTOQ2 {
        public static void main(String[] args) {
           // dodo dodo1 = new dodo();
            dodo dodo2 =new dodo(){public String get(){return "filan";}};
            dodo.brain b = dodo2.new brain(){public String get(){return "stored ";}};
            System.out.print(dodo2.get()+" ");
            System.out.println(b.get());
    abstract class dodo
        public String get()
            return "poll";
        abstract class brain
            public abstract String get();
    }I know that abstract classes cannot be instantiated but i see that in this example, with a nested anonymous class it does (dodo and brain classes). My guess is that declaring the nested class it makes a subclass of the abstract class and doing so it can be instantiated. But i can't find any documentation about this.
    Does anybody know?
    Really thanks in advance.
    Regards,
    Christian Vielma

    cvielma wrote:
    Another question about this. Why can't i declare a constructor in the nested class? (it gives me return type required)You cannot declare a constructor, because in one line you're declaring a new class (the anonymous inner class) as well as constructing an instance of it.
    What you can do, however, is if the abstract class (or the superclass, in any case, it doesn't need to be abstract) defines several constructors, you can call them.
    public abstract MyClass {
        public MyClass() {
            // Default do nothing constructor
        public MyClass(String s) {
            // Another constructor
    // Elsewhere
    MyClass myclass = new MyClass("Calling the string constructor") {
    };But you can't define your own constructors in the anonymous inner class.
    Also, since the class is anonymous, what would you name the constructor? :)
    Edited by: Kayaman on 26.6.2010 22:37

  • Class implementing its own inner interface?

    Hi
    If I try to compile the following I get a "cyclic inheritance involving Data_set" compiler error on line 1:
        public class Data_set implements Data_set.Row
            public interface Row
                String column(final int a_index);
            public String column(final int a_index)
                return "something";
            public Row row(final int a_index)
                return new Row_impl();
            private class Row_impl
                implements Row
                public String column(final int a_index)
                    return "something else";
        }Is there any good logical reason why this should be disallowed, given that the interface is necessarily static and putting it inside the class seems like just a namespace issue that would involve no cyclic dependencies?
    Thanks
    Colin

    colin_chambers wrote:
    The Row component here only has meaning with respect to the Data_set container, so I do think that it makes sense to scope the Row name inside Data_set I respectfully disagree. Row is much more independent of a set of Rows than a DataSet is from Rows. A row can live on its own, a data set cannot. Your domain modeling is iffy at best.
    I would find it extra syntactic clutter to extract the row explicitly in these cases.You should never resort to a poor design to avoid "syntactic clutter", and it's quite likely that a proper design will reduce the clutter. My guess is that you've got a bad design through and through, and should consider maybe an inversion of control? Maybe what you're really looking for is a [Visitor pattern|http://en.wikipedia.org/wiki/Visitor_pattern]?
    public interface RowVisitor {
       void visitRow(Row row);
    public interface RowVisitable {
       void acceptRowVisitor(RowVisitor visitor);
    public class Row extends RowVisitable {
       public void acceptRowVisitor(RowVisitor visitor) {
          visitor.visitRow(this);
       //...other stuff
    public class DataSet implements RowVisitable {
       private final Collection<RowVisitable> children;
       public void acceptRowVisitor(RowVisitor visitor) {
          for ( RowVisitable row : children ) {
             row.acceptRowVisitor(visitor);
    DataSet set;
    RowVisitor printVisitor = new RowVisitor() {
       public void visitRow(Row row) {
          System.out.println(row);
    set.acceptRowVisitor(printVisitor);Another option would be an Iterator pattern.

  • IllegalAccessError when trying to create a proxy for a non-public interface

    My code proxies a class that extends JDialog. Under Java5 this works fine. However when I switch to Java6 I get a java.lang.IllegalAccessError: class javax.swing.$Proxy3 cannot access its superinterface javax.swing.TransferHandler$HasGetTransferHandler exception.
    I went through debugging my code to find out what went wrong. I created the included test code that shows the problem (and because the real codebase is much too big to include here).
    package javax.swing;
    public class SomePackageInterfaceDefiningClass {
        interface SomeInnerPackageInterface {
    package javax.swing;
    import java.lang.reflect.Proxy;
    import java.util.ArrayList;
    import java.util.Collection;
    import org.apache.commons.lang.ArrayUtils;
    public class NonPublicInterfaceProxyCreator {
        public static void main(String[] args) {
            // This works fine !
            doTest(WindowConstants.class);
            // This also ! The proxy class package is javax.swing as expected
            doTest(SomePackageInterfaceDefiningClass.SomeInnerPackageInterface.class);
            // JDialog implements the package visible interface
            // javax.swing.TransferHandler.HasGetTransferHandler
            Collection<Class<?>> jdInterfaces = new ArrayList<Class<?>>();
            for (Class<?> interfaze : JDialog.class.getInterfaces()) {
                jdInterfaces.add(interfaze);
            Collection<Class<?>> strippedJdialogInterfaces = new ArrayList<Class<?>>(
                    jdInterfaces);
            for (Class<?> interfaze : jdInterfaces) {
                if (interfaze.getName().equalsIgnoreCase(
                        "javax.swing.TransferHandler$HasGetTransferHandler")) {
                    strippedJdialogInterfaces.remove(interfaze);
            // Without the package visible interface it works !
            doTest(strippedJdialogInterfaces.toArray(new Class<?>[0]));
            // With the package visible interface it fails
            doTest(jdInterfaces.toArray(new Class<?>[0]));
        private static void doTest(Class... interfaces) {
            // Class clazz = Proxy.getProxyClass(JDialog.class.getClassLoader(),
            // interfaces);
            Class clazz = Proxy.getProxyClass(Thread.currentThread()
                    .getContextClassLoader(), interfaces);
            System.out.println("Class created = " + clazz
                    + " >>>> Implemented interfaces = "
                    + ArrayUtils.toString(clazz.getInterfaces()));
    }When I run this code under Java5 I get:
    Class created = class $Proxy0 >>>> Implemented interfaces = {interface javax.swing.WindowConstants}
    Class created = class javax.swing.$Proxy1 >>>> Implemented interfaces = {interface javax.swing.SomePackageInterfaceDefiningClass$SomeInnerPackageInterface}
    Class created = class $Proxy2 >>>> Implemented interfaces = {interface javax.swing.WindowConstants,interface javax.accessibility.Accessible,interface javax.swing.RootPaneContainer}
    Class created = class $Proxy2 >>>> Implemented interfaces = {interface javax.swing.WindowConstants,interface javax.accessibility.Accessible,interface javax.swing.RootPaneContainer}Under Java6 I get:
    Class created = class $Proxy0 >>>> Implemented interfaces = {interface javax.swing.WindowConstants}
    Class created = class javax.swing.$Proxy1 >>>> Implemented interfaces = {interface javax.swing.SomePackageInterfaceDefiningClass$SomeInnerPackageInterface}
    Class created = class $Proxy2 >>>> Implemented interfaces = {interface javax.swing.WindowConstants,interface javax.accessibility.Accessible,interface javax.swing.RootPaneContainer}
    Exception in thread "main" java.lang.IllegalAccessError: class javax.swing.$Proxy3 cannot access its superinterface javax.swing.TransferHandler$HasGetTransferHandler
         at java.lang.reflect.Proxy.defineClass0(Native Method)
         at java.lang.reflect.Proxy.getProxyClass(Proxy.java:504)
         at javax.swing.NonPublicInterfaceProxyCreator.doTest(NonPublicInterfaceProxyCreator.java:45)
         at javax.swing.NonPublicInterfaceProxyCreator.main(NonPublicInterfaceProxyCreator.java:38)According to the documentation the interface javax.swing.TransferHandler$HasGetTransferHandler should be visible to my class as it is located in the same package, right?
    I think there must be some classloading issue when trying to access the non-public interface javax.swing.TransferHandler$HasGetTransferHandler in rt.jar.
    I can not figure out what is different between my own non-public interface and Swing's javax.swing.TransferHandler$HasGetTransferHandler.
    Any help would be appreciated.

    I don't agree completely. What you're telling is true, don't get me wrong. It's the Error that I get from Java that troubles me.
    To resolve the classloading question, I changed my code as follows:
    package javax.swing;
    import java.lang.reflect.Proxy;
    import java.util.ArrayList;
    import java.util.Collection;
    import org.apache.commons.lang.ArrayUtils;
    public class NonPublicInterfaceProxyCreator {
        public static void main(String[] args) {
            // This works fine !
            doTest(WindowConstants.class);
            doTest2(WindowConstants.class);
            // This also ! The proxy class package is javax.swing as expected
            doTest(SomePackageInterfaceDefiningClass.SomeInnerPackageInterface.class);
            doTest2(SomePackageInterfaceDefiningClass.SomeInnerPackageInterface.class);
            // JDialog implements the package visible interface
            // javax.swing.TransferHandler.HasGetTransferHandler
            Collection<Class<?>> jdInterfaces = new ArrayList<Class<?>>();
            for (Class<?> interfaze : JDialog.class.getInterfaces()) {
                jdInterfaces.add(interfaze);
            Collection<Class<?>> strippedJdialogInterfaces = new ArrayList<Class<?>>(
                    jdInterfaces);
            for (Class<?> interfaze : jdInterfaces) {
                if (interfaze.getName().equalsIgnoreCase(
                        "javax.swing.TransferHandler$HasGetTransferHandler")) {
                    strippedJdialogInterfaces.remove(interfaze);
            // Without the package visible interface it works !
            doTest(strippedJdialogInterfaces.toArray(new Class<?>[0]));
            doTest2(strippedJdialogInterfaces.toArray(new Class<?>[0]));
            // With the package visible interface it fails
            doTest(jdInterfaces.toArray(new Class<?>[0]));
            doTest2(jdInterfaces.toArray(new Class<?>[0]));
        private static void doTest(Class... interfaces) {
            ClassLoader contextClassLoader = Thread.currentThread()
                    .getContextClassLoader();
            System.out.println("Classloader that creates proxy = " + contextClassLoader);
            try {
                Class clazz = Proxy.getProxyClass(contextClassLoader, interfaces);
                System.out.println("Class created = " + clazz
                        + " >>>> Implemented interfaces = "
                        + ArrayUtils.toString(clazz.getInterfaces()));
            } catch (Throwable e) {
                e.printStackTrace();
        private static void doTest2(Class... interfaces) {
            ClassLoader contextClassLoader = JDialog.class.getClassLoader();
            System.out.println("Classloader that creates proxy = " + contextClassLoader);
            try {
                Class clazz = Proxy.getProxyClass(contextClassLoader, interfaces);
                System.out.println("Class created = " + clazz
                        + " >>>> Implemented interfaces = "
                        + ArrayUtils.toString(clazz.getInterfaces()));
            } catch (Throwable e) {
                e.printStackTrace();
    }And here is the result when I run it on Java 1.6:
    Classloader that creates proxy = sun.misc.Launcher$AppClassLoader@11b86e7
    Class created = class $Proxy0 >>>> Implemented interfaces = {interface javax.swing.WindowConstants}
    Classloader that creates proxy = null
    Class created = class $Proxy1 >>>> Implemented interfaces = {interface javax.swing.WindowConstants}
    Classloader that creates proxy = sun.misc.Launcher$AppClassLoader@11b86e7
    Class created = class javax.swing.$Proxy2 >>>> Implemented interfaces = {interface javax.swing.SomePackageInterfaceDefiningClass$SomeInnerPackageInterface}
    Classloader that creates proxy = null
    java.lang.IllegalArgumentException: interface javax.swing.SomePackageInterfaceDefiningClass$SomeInnerPackageInterface is not visible from class loader
         at java.lang.reflect.Proxy.getProxyClass(Proxy.java:353)
         at javax.swing.NonPublicInterfaceProxyCreator.doTest2(NonPublicInterfaceProxyCreator.java:64)
         at javax.swing.NonPublicInterfaceProxyCreator.main(NonPublicInterfaceProxyCreator.java:18)
    Classloader that creates proxy = sun.misc.Launcher$AppClassLoader@11b86e7
    Class created = class $Proxy3 >>>> Implemented interfaces = {interface javax.swing.WindowConstants,interface javax.accessibility.Accessible,interface javax.swing.RootPaneContainer}
    Classloader that creates proxy = null
    Class created = class $Proxy4 >>>> Implemented interfaces = {interface javax.swing.WindowConstants,interface javax.accessibility.Accessible,interface javax.swing.RootPaneContainer}
    Classloader that creates proxy = sun.misc.Launcher$AppClassLoader@11b86e7
    java.lang.IllegalAccessError: class javax.swing.$Proxy5 cannot access its superinterface javax.swing.TransferHandler$HasGetTransferHandler
         at java.lang.reflect.Proxy.defineClass0(Native Method)
         at java.lang.reflect.Proxy.getProxyClass(Proxy.java:504)
         at javax.swing.NonPublicInterfaceProxyCreator.doTest(NonPublicInterfaceProxyCreator.java:51)
         at javax.swing.NonPublicInterfaceProxyCreator.main(NonPublicInterfaceProxyCreator.java:41)
    Classloader that creates proxy = null
    Class created = class javax.swing.$Proxy6 >>>> Implemented interfaces = {interface javax.swing.WindowConstants,interface javax.accessibility.Accessible,interface javax.swing.RootPaneContainer,interface javax.swing.TransferHandler$HasGetTransferHandler}As you can see, I get an IllegalArgumantException telling me that my interface I try to proxy is not visible for JDialog's classloader, as I would expect. Remark that Java tells me that JDialog's classloader is null. Strange, isn't is?
    However I get an IllegalAccessError when I try to proxy TransferHandler$HasGetTransferHandler from my own classloader.
    Any reason why the error is different?

  • Cann't extend a inner class where as can Implement a nested Interface

    i cann't extend a inner class in some other outer class . Where as i can implement the nested Interface in some other class. Why????
    for example:-
    class ABC
    class Inner
    /* class body */
    interface TempInterface
    /* interfacebody */
    class OuterClass
    class InnerTwo extends ABC.inner //(line 1)Will give error
    class InnerTwo implements ABC.TempInterface //(line 2)Will run fine
    the line 1 is going to give compilation error i.e not in the scope but the line 2 will run fine .
    Both of the things are in the same class but giving 2 other results.
    I am not getting sufficient reasons for it.
    Can any one help me????
    Reagrds
    Arunabh

    As far as the language is concerned, the classonly
    exists in the context of an instance of theenclosing
    class.This still exhibits a class/object confusion to me.
    It should be 'instance only exists ...' or 'instance
    can only exist'. The class only exists in the
    scope of the enclosing class, but this is another
    issue.I'm not following what you're saying. The second sentence sounds like you're disagreeing with me. The last sentence sounds like you're agreeing with me.
    A non-static nested class is an instance member, just like an instance method or instance variable. As such, as far as the language is concerned, that class only exists in the context of an instance of the enlcosing class.It's not just instances of the nested class--its the class definition itself that only exists within the context of an instance of the enclosing class. That's why you have to do anEclosingIntstance.NestedClass and can't do EnclosingClass.NestedClass.

  • Force Derived Class to Implement Static Method C#

    So the situation is like, I have few classes, all of which have a standard CRUD methods but static. I want to create a base class which will be inherited so that it can force to implement this CRUD methods. But the problem is, the CRUD methods are static. So
    I'm unable to create virtual methods with static (for obvious reasons). Is there anyway I can implement this without compromising on static.
    Also, the signature of these CRUD methods are similar.
    E.g. ClassA will have CRUD methods with these type of Signatures
    public static List<ClassA> Get()
    public static ClassA Get(int ID)
    public static bool Insert(ClassA objA)
    public static bool Update(int ID)
    public static bool Delete(int ID)
    ClassB will have CRUD signatures like
    public static List<ClassB> Get()
    public static ClassB Get(int ID)
    public static bool Insert(ClassB objB)
    public static bool Update(int ID)
    public static bool Delete(int ID)
    So I want to create a base class with exact similar signature, so that inherited derived methods will implement their own version.
    For E.g. BaseClass will have CRUD methods like
    public virtual static List<BaseClass> Get()
    public virtual static BaseClassGet(int ID)
    public virtual static bool Insert(BaseClass objBase)
    public virtual static bool Update(int ID)
    public virtual static bool Delete(int ID)
    But the problem is I can't use virtual and static due to it's ovbious logic which will fail and have no meaning.
    So is there any way out?
    Also, I have few common variables (constants) which I want to declare in that base class so that I don't need to declare them on each derived class. That's why i can't go with interface also.
    Anything that can be done with Abstract class?

    Hi,
    With static methods, this is absolutely useless.
    Instead, you could use the "Singleton" pattern which restrict a class to have only one instance at a time.
    To implement a class which has the singleton pattern principle, you make a sealed class with a private constructor, and the main instance which is to be accessed is a readonly static member.
    For example :
    sealed class Singleton
    //Some methods
    void Method1() { }
    int Method2() { return 5; }
    //The private constructor
    private Singleton() { }
    //And, most importantly, the only instance to be accessed
    private static readonly _instance = new Singleton();
    //The corresponding property for public access
    public static Instance { get { return _instance; } }
    And then you can access it this way :
    Singleton.Instance.Method1();
    Now, to have a "mold" for this, you could make an interface with the methods you want, and then implement it in a singleton class :
    interface ICRUD<BaseClass>
    List<BaseClass> GetList();
    BaseClass Get(int ID);
    bool Insert(BaseClass objB);
    bool Update(int ID);
    bool Delete(int ID);
    And then an example of singleton class :
    sealed class CRUDClassA : ICRUD<ClassA>
    public List<ClassA> GetList()
    //Make your own impl.
    throw new NotImplementedException();
    public ClassA Get(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Insert(ClassA objA)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Update(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    public bool Delete(int ID)
    //Make your own impl.
    throw new NotImplementedException();
    private CRUDClassA() { }
    private static readonly _instance = new CRUDClassA();
    public static Instance { get { return _instance; } }
    That should solve your problem, I think...
    Philippe

  • Why method local inner class can use final variable rather than....

    Hi all
    Just a quick question.
    Why method-local inner class can access final variable defined in method only?
    I know the reason why it can not access instance variable in method.
    Just can not figure out why??
    any reply would be appreciated.
    Steven

    Local classes can most definitely reference instance variables. The reason they cannot reference non final local variables is because the local class instance can remain in memory after the method returns. When the method returns the local variables go out of scope, so a copy of them is needed. If the variables weren't final then the copy of the variable in the method could change, while the copy in the local class didn't, so they'd be out of synch.

  • What class that can implement file transfer in j2sdk

    hi
    i am doing this project that can transfer file through LAN(much like Yahoo Messenger)
    is there a class in j2sdk that can implement this? how to do it?
    thanks>>>>

    Annie is right that if you use only j2sdk then you want to use java.net. If you want to do it an easier way you can use ftp and download open source code. There are a couple of free packages you can find at http://www.javaworld.com/javaworld/jw-04-2003/jw-0404-ftp-p2.html
    If you want to use only the j2sdk then these 2 classes will give you an example of how to transfer data on the net. You need to add a lot more code to make these useful but it gives the general idea of how to open a socket and tranfser a bit of data.
    Client Side
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class ClientClass {
         private final static String HOST = "10.133.5.230";
         private final static int PORT = 543;
         public void sendFile() {
              try {
                   System.out.println("Entered sendFile");
                   Socket socket = new Socket( HOST, PORT);
                   InputStreamReader input = new InputStreamReader(socket
                             .getInputStream());
                   PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
                   output.println("This is a test");
                   output.println("This is a test 2");
                   output.println("Last line");
                   output.println("ENDEND");
                   socket.close();
              } catch (Exception ex) {
                   ex.printStackTrace();
         public static void main(String[] args) {
              ClientClass client = new ClientClass();
              client.sendFile();
    }Server Side
    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;
    public class ServerClass {
         private final static String HOST = "10.133.5.230";
         private final static int PORT = 543;
         public void getFile() {
              char[] inbuf = new char[2048];
              try {
                   System.out.println("Entered getFile");
                   // open server
                   ServerSocket server = new ServerSocket(PORT);
                   // wait for client.
                   Socket client = server.accept();
                   InputStreamReader inputStream = new InputStreamReader(client
                             .getInputStream());
                   BufferedReader input = new BufferedReader(inputStream);
                   PrintWriter output = new PrintWriter(client.getOutputStream());
                   while (true) {
                        String inData = input.readLine();
                        if ((inData != null) && (inData.length() > 0)) {
                             System.out.println("got '" + inData + "'");
                             if (inData.indexOf("ENDEND") > -1) {
                                  client.close();
                                  server.close();
                                  System.exit(0);
              } catch (Exception ex) {
                   ex.printStackTrace();
         public static void main(String[] args) {
              ServerClass server = new ServerClass();
              server.getFile();
    }Start the server side first and then run the client code in a separate JVM.
    You will also need to add the ability to handle binary and some sort of protocol to transfer the file names and handle the exceptions much better. Doing it like this would be much more fun and challenging, with ftp it would be alot faster.

  • How do i create a static function in a class and implement ActionListener?

    i am trying to create a pop up dialog box in a seperate class.
    and i want to make the Function static, so that i only need to access it with the class name.
    But how do i have a ActionListener ?
    everything in a static function is static rite?

    import java.awt.*;
    import java.awt.event.*;
    public class StaticFunction
        Dialog dialog;
        private Panel getUIPanel()
            Button button = new Button("show dialog");
            button.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    if(dialog == null)
                        dialog = OutsideUtility.showDialog("hello world");
                    else if(!dialog.isVisible())
                        dialog.setVisible(true);
                    else if(dialog.isVisible())
                        dialog.dispose();
                        dialog = null;
            Panel panel = new Panel();
            panel.add(button);
            return panel;
        private WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                System.exit(0);
        public static void main(String[] args)
            StaticFunction sf = new StaticFunction();
            Frame f = new Frame();
            f.addWindowListener(sf.closer);
            f.add(sf.getUIPanel());
            f.setSize(200,100);
            f.setLocation(200,200);
            f.setVisible(true);
    class OutsideUtility
        public static Dialog showDialog(String msg)
            Button button = new Button("top button");
            button.setActionCommand(msg);
            button.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    Button button = (Button)e.getSource();
                    System.out.println(button.getActionCommand() +
                                       " from anonymous inner listener");
            button.addActionListener(new ButtonListener());
            Button anotherButton = new Button("bottom button");
            anotherButton.setActionCommand("another button");
            anotherButton.addActionListener(localListener);
            Panel north = new Panel();
            north.add(button);
            Panel south = new Panel();
            south.add(anotherButton);
            Dialog dialog = new Dialog(new Frame());
            dialog.addWindowListener(closer);
            dialog.add(north, "North");
            dialog.add(new Label(msg, Label.CENTER));
            dialog.add(south, "South");
            dialog.setSize(200,200);
            dialog.setLocation(425,200);
            dialog.setVisible(true);
            return dialog;
        private static WindowListener closer = new WindowAdapter()
            public void windowClosing(WindowEvent e)
                Dialog dialog = (Dialog)e.getSource();
                dialog.dispose();
        private static ActionListener localListener = new ActionListener()
            public void actionPerformed(ActionEvent e)
                Button button = (Button)e.getSource();
                System.out.println(button.getActionCommand() +
                                   " from localListener");
        private static class ButtonListener implements ActionListener
            public void actionPerformed(ActionEvent e)
                Button button = (Button)e.getSource();
                String ac = button.getActionCommand();
                System.out.println(ac + " from ButtonListener");
    }

  • Can a class implements more than one interface?

    Hello
    Can a class implements more than one interface?
    Thanks

    Of course, this doesn't mean that it won't be a problem though. If the two interfaces have methods with the same signature, but different return types, you won't be able to implement them together. I.E.
    interface InterfaceA {
      public int doSomething(String myString);
    interface InterfaceB {
      public String doSomething(String myString);
    // Now the classes
    // Gives error "Duplicate method doSomething(String) in type ClassA"
    public class ClassA implements InterfaceA, InterfaceB {
      public int doSomething(String myString) {
        System.out.println("A");
        return 0;
      public String doSomething(String myString) {
        System.out.println("B");
        return 0;
    // Gives error "The return type is incompatible with InterfaceB.doSomething(String)"
    public class ClassB implements InterfaceA, InterfaceB {
      public int doSomething(String myString) {
        System.out.println("A");
        return 0;
    // Gives error "The return type is incompatible with InterfaceA.doSomething(String)"
    public class ClassC implements InterfaceA, InterfaceB {
      public String doSomething(String myString) {
        System.out.println("B");
        return 0;
    }

  • Is there any way an iPhone app developer can implement low power class 3 Bluetooth?

    Is there any way an iPhone app developer can implement low power class 3 Bluetooth?

    Ah-HA!  I knew there had to be a way!
    Not quite the same in 10.6, but close enough to find it:
    It's iTunes>apps, not iTunes>iPhone>apps.  I didn't realize there were different windows.
    Not double-click, but control-click.  Close enough.
    Easy-Peasy, now that you showed me how.
    Thanks, Barry.
    --Gil

  • Compiler says class can't be initialized

    ok, i know abstract classes can't be initialized, but i am extending my base class, but my complier says that "class ClassificationParser can't be initialized" but i am not initializing it. IF anyone can point out a problem, which i just can't see please do. Thank you..
    first is listed the base abstract class, second the extended class
    package cattlemanager.utilities.parsers;
    import java.util.Vector;
    import java.io.File;
    import java.io.IOException;
    * Title:        ClassificationParser
    * Copyright:    Copyright (c) 2001
    * Company:      None
    * @author Harold Smith III
    * @version 1.0
    public abstract class ClassificationParser
       * <p>This method returns the instance of a <code>Classification</code> objects
       * that the implementor can work with and use to there own extent. This allows
       * for the parser to read in all the file data, and insert it into the
       * <code>Classification</code> Objects that he or she wishes the user to
       * modify.</p>
       * <p><strong>Important</strong> - The <code>Vector</code> that is returned will
       *  contain a <code>Vector</code> of <code>Vector</code>'s that the implementor
       *  must work with. The reason for a <code>Vector</code> of <code>Vector</code>'s
       *  is the <code>Classification</code> data may contain several past <code>
       *  Classification</code> records.</p>
       * @return Vector the data vector.
      public Vector getData()
      { return vInternalClassificationDataObject;
       * <code>parse</code> is the default parsing mechanism for the read in data
       * that the user can integrate into there records. Using the <code>parse</code>
       * method, the implemented class will read in the specified <code>File</code>
       * and the <code>Classification</code> Objects will be initialized with tthe
       * read in data.
       * @param File the file to be parsed, should follow the specified format
       *  determined by the appropriate association.
       * @throws WrongFormatException if the file is not formatted to the standards
       *  the association has laid out.
       * @throws IOException if there is a file problem.
      public abstract void parse(File fName) throws WrongFormatException, IOException;
       * The internal <code>Vector</code> of objects that will be laid out as specified
       * in the <code>getData</code> method described within this class.
       * @see #getData
      protected Vector vInternalClassificationDataObject;
    package cattlemanager.utilities.parsers;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.DataInputStream;
    import java.io.IOException;
    import java.io.EOFException;
    import java.util.StringTokenizer;
    import java.util.Date;
    import java.util.GregorianCalendar;
    * Title:        HolsteinAssociationClassificationParser
    * Copyright:    Copyright (c) 2001
    * Company:      None
    * @author Harold Smith III
    * @version 1.0
    public class HolsteinAssociationClassificationParser extends ClassificationParser
      private HolsteinAssociationClassificationParser()
      { try
        { parse(new File("demo.ext"));
        catch (Exception e)
       * Doesn't work?!
      public static synchronized ClassificationParser createInstance()
      { return new HolsteinAssociationClassificationParser();
       * <code>parse</code> parses the <a href="www.holstein.com">Holstein
       *  Association</a> classification data as laid out in there <code>File</code>
       *  format. By using this parser, one can read in the records and access the
       *  data that they need.
       * @param File the name of the file to be parsed.
       * @throws WrongFormatException if the file is not properly formated
      private void parse(File fName) throws WrongFormatException, IOException
        try {
          // READ IN FILE
       * Creates an instance of a date for the format specified by the Holstein
       * Association
      private Date createDate(String time)
      { GregorianCalendar c = (GregorianCalendar) GregorianCalendar.getInstance();
        c.set(Integer.parseInt(time.substring(0,4)), Integer.parseInt(time.substring(4,6))-1, Integer.parseInt(time.substring(6,8)));
        return c.getTime();
    }

    ah stupid errors, i figured it out, i accidently created an instance in a class before i decided to change the class to abstract!

  • Why not static methods in an Interface

    why can't i make static methods part of an Interface?
    for example:
    public interface Names {
        public static String[] getNames(); // <--- "static" not allowed in an Interface.
    }what i want to say is:
    every class that implements the Names interface must have a static method, getNames() , that returns a raw array of Strings.
    why won't jave let me do this with an Interface?
    Edited by: kogose on Feb 4, 2009 5:47 PM

    this is my current solution:
    public interface Symbols {
        public String[] getSymbols();
    public class ETF implements Symbols {
        public String[] getSymbols() {
            return(ETF.symbols);
        private static String[] symbols =    { "DIG", "UYM", ...... }
    public class INDEXES implements Symbols {
        public String[] getSymbols() { return(symbols); }
        private static String[] symbols = { "^DZC", "^UTIL", "^GWI", .... }
    public class NYSE implements Symbols {
        public String[] getSymbols() {
            return(NYSE.symbols);
        private static String[] symbols =  { "GDL", "GDI", .... }
    }then to get the data:
    analyzer.analyze((new ETF()).getSymbols());
    analyzer.analyze((new INDEXES()).getSymbols());
    analyzer.analyze((new NYSE()).getSymbols());
    this looks like a hack to me?
    its weird that i create an object just to invoke one method and get static data.....
    is there an elegant way?

  • Why interfaces why not abstract classes?

    why they are using interfaces concept in JDBC or struts2.0 why not abstract classes?
    thanks in advance.

    user5287726 wrote:
    jverd wrote:
    user5287726 wrote:
    Interfaces are more flexible. For certain definitions of flexible, yes, but not for others.
    A Java class can only inherit one class, but it can implement multiple interfaces.Which has absolutely nothing to do with why JDBC declares interfaces rather than abstract classes.How does your post even attempt to answer the OP's question?OP asked: "why they are using interfaces concept in JDBC or struts2.0 why not abstract classes?" I'm pointing out that your post does not address the question asked. And of course your answer is wrong anyway.
    As for addressing the OP's question, I did that in my first response.

Maybe you are looking for