Why does interfaces allow class definitions within them

Can anybody explain why interfaces can contain class definitions.

Saish wrote:
It does somewhat adulterate the idea that interfaces and implementations should be separate. I would find it more useful if the class that you declare could be something other than public. That way, you could expose an interface, a factory (which would be public) and then have all the implementations private in the same file. A client would only see the factory and the interface (granted, one could achieve the same effect with non public classes in their own source files all in the same package). But to require that member types within the interface be public, that really makes little sense to me.agreed - this limitation is quite annoying. Forces me to use extra level of nesting to work around it:
// see also: http://forums.sun.com/thread.jspa?messageID=10938789#10938789
public interface MyInfo {
  public MyStatus getMyStatus();
  public static interface MyStatus { } // MyStatus
  public static class Factory {
    public static MyStatus newMyInfo() {
      return new MyInfo() {
        public MyStatus getMyStatus() {
          return new Innards.MyStatusImpl();
  } // Factory
  // IMPL NOTE purpose of this class is to keep implementation details inside
  public final /* IMPL NOTE subclassing prohibited */ static class Innards {
    private Innards() {}  /* IMPL NOTE instantiation prohibited */
    private static class MyStatusImpl implements MyStatus { } // MyStatusImpl
  } // Innards
} // MyInfo

Similar Messages

  • Please! WHY? Why does the main class cannot find symbol symbol : constructor Car(double) location: class Car?

    Why does the main class cannot find symbol symbol : constructor Car(double) location:
    class Car .. ??
    class Car
    { //variable declaration
    double milesStart; double milesEnd; double gallons;
    //constructors
    public Car(double start, double end, double gall)
    { milesStart = start; milesEnd = end; gallons = gall; }
    void fillUp(double milesE, double gall)
    { milesEnd = milesE; gallons = gall; }
    //methods
    double calculateMPG()
    { return (milesEnd - milesStart)/gallons; }
    boolean gashog() { if(calculateMPG()<15) { return true; } else { return false; } }
    boolean economycar() { if(calculateMPG()>30) { return true; } else { return false; } } }
    import java.util.*; class MilesPerGallon
    { public static void main(String[] args)
         double milesS, milesE, gallonsU;
         Scanner scan = new Scanner(System.in);
         System.out.println(\"New car odometer reading: 00000\");
          Car car = new Car(milesS); car.fillUp(milesE, gallonsU);
         System.out.println(\"New Miles: \" + milesE); milesE = scan.nextDouble();
         System.out.println(\"Gallons used: \" + gallonsU);
         gallonsU = scan.nextDouble();
         System.out.println( \"MPG: \" + car.calculateMPG() );
         if(car.gashog()==true) { System.out.println(\"Gas Hog!\");
          if(car.economycar()==true) { System.out.println(\"Economy Car!\");
         } System.out.println(\"\");
         milesS = milesS + milesE;
         System.out.println(\"Enter new miles\");
          milesE = scan.nextDouble();
         System.out.println(\"Enter gallons used: \");
          gallonsU = scan.nextDouble();
         car.fillUp(milesE, gallonsU);
         System.out.println(\"Initial miles: \" + milesS);
         System.out.println(\"New Miles: \" + milesE);
         System.out.println(\"Gallons used: \" + gallonsU);
         System.out.println( \"MPG: \" + car.calculateMPG() );
         System.out.println(\"\"); } }

    Why does the main class cannot find symbol symbol : constructor Car(double) location:
    class Car .. ??
    Please tell us which line of code you posted shows 'Car (double)'.
    The only constructor that I see is this one:
    Car(double start, double end, double gall)

  • Why does Labview allow a cursor in a indicator?

    Hello,
        Why does Labview allow the user to position the cursor with the mouse inside a numeric indicator? Users think that just because they can put a cursor they should be able to type something and enter data. Is there a way to disable/stop the user from putting the cursor in a numeric indicator?
    Regards,
    Kaspar
    Solved!
    Go to Solution.

    Disabling the indicator satisfies your requirements, but this is funnier.  It would be even better if I calculated the position of the indicator and the "entry point" and just kept the mouse from entering, but I have a project to finish... 
    Message Edited by jcarmody on 03-27-2009 11:58 AM
    Jim
    You're entirely bonkers. But I'll tell you a secret. All the best people are. ~ Alice
    Attachments:
    move.png ‏4 KB
    test.vi ‏9 KB

  • Why does LabVIEW allow me to have 2 controls with same name

    Here's a general LabVIEW question:
    Why does LabVIEW allow me to have 2 controls with the same name in the same VI?  It seems like this only increases the chances of confusion.  Especially when someone is just looking at a block diagram (or documentation of a block diagram).
    No other programming language that I know of allows this.  I realize that uniqueness of name is not as critical in LabVIEW as it is in any text based language.  For example, in a text based language, if I had 2 variables called abc and I wrote a statement
    abc = 12;
    the compiler would not know which abc was being referred to.  In LabVIEW, if we had 2 controls called abc, the equivalent of doing an abc=12 is writing to a local variable (which is always linked to one of the controls) and there is no ambiguity.  Still, someone looking at the code cannot figure out which abc is linked to unless he does a right click>>Find>>terminal (or a double click).
    Even though I have never and never will name 2 controls the same, I think it would be a nice constraint to see enforced by LabVIEW.
    Any input from NI engineers on this?
    Message Edited by S G on 12-18-2007 03:38 PM
    S G
    Certified LabVIEW Architect, Certified TestStand Developer, Certified Professional Instructor
    Attachments:
    Trial1.JPG ‏21 KB

    I know when you copy and paste a control or indicator, LabVIEW automatically increments the label. But since you can hide the label, and show or hide the caption, there must be another mechanism that LabVIEW uses to keep track of all the controls. I thought I remember back in the "old days" (ver 6 or 6i) LabVIEW would give you an error if you tried to make two controls with the same name. Perhaps that was LabWindows/CVI.
    I don't know where the index is actually stored, but if you look at a property node linked to the Pane, you will see an array of references to the controls and indicators. Since the references are stored in an array, I assume that any local variables are tied to the index of that array. Since the labels themselves are properties of the control, I guess there's no reason to limit what that label is. They all have a unique index number.
    Interestingly, this array of references grows from the beginning. That is, any new control or indicator is put at index 0, not the end of the array.
    B-)
    Message Edited by LabViewGuruWannabe on 12-18-2007 08:45 PM
    Attachments:
    Labels.png ‏12 KB

  • Why does apple allow apps in the App Store hijack your Internet when certain websites? Why doesn't apple remove their products from the App Store?.

    Why does apple allow apps in the App Store hijack your Internet when certain websites? Why doesn't apple remove their products from the App Store?.

    Apple saw it as their responsibility since the redirection took me to the App Store. They assisted me in stopping the redirection which is occurring on many peoples iPhones. It's a have java script problem that adking is using to get you to buy their games. The websites work normal and then all of the sudden the website is taken over by adking.com.  You can no longer use the website as it immediately takes you to the App Store without ever showing a popup to cancel the redirection. They were very helpful fixing the problem should others experiencing this specifically with adking.com.
    No need to get defensive. I'm not the only one experiencing the problem Apple said.

  • Why does Java allow this?

    Hello Folks
    Today I saw the following code in an exam about Java programming:
    interface I {
         public final static double var = 32.0;
    class A implements I {
         double var = 15;
    }How can Java allow such a construct? I overload a variable that is public, static and final and replace it with an instance variable that is protected. In my opinion the compiler should reject that, I mean it does it when I try the same with a method. Why is it allowed with variables?
    Regards
    Der Hinterwaeldler

    The declaration of the variable var in class A does not override the declaration in the interface I, it only hides it.
    Methods are different because methods can be overridden. Static and final methods are an exception, they can't be overridden so trying to do it is a compile time error.
    See also http://java.sun.com/developer/TechTips/2000/tt1010.html#tip2

  • Why does this abstract class and method work without implement it?

    hi,
    I have seen many times that in some examples that there are objects made from abstract classes directly. However, in all books, manual and tutorials that I've read explain that we MUST implement those methods in a subclass.
    An example of what I'm saying is the example code here . In a few words that example makes Channels (java.nio.channel) and does operations with them. My problem is in the class to make this channels, because they used the ServerSockeChannel class and socket() method directly despite they are abstracts.
       // Create a new channel: if port == 0, FileChannel on /dev/tty, else
       // a SocketChannel from the first accept on the given port number
    private static ByteChannel newChannel (int netPort)
          throws Exception
          if (netPort == 0) {
             FileInputStream fis = new FileInputStream ("/dev/tty");
             return (fis.getChannel());
          } else {
    //CONFLICT LINES
             ServerSocketChannel ssc = ServerSocketChannel.open(); //<--I have never thought do that!! Anyway, how it is static method may work.
             ssc.socket().bind (new InetSocketAddress (netPort)); //<--but here, this method (socket) is abstract. WHY RETURN A SOCKET????????  this mehod should be empty by default.
             System.out.print ("Waiting for connection on port "
                + netPort + "...");
             System.out.flush();
             ByteChannel channel = ssc.accept();
             ssc.close();
             System.out.println ("Got it");
             return (channel);
       } I test this code and works fine. So why can it be??
    Also, I read that the abstract classes can't have static methods. Is it true???
    Please Help!!
    PS: i have seen this kind of code many times. So i feel that I don't understand how its really the abstract methods are made.
    PS2: I understand that obviously you don't do something like this: *"obj = new AbstractClass(); "*. I dont understand how it could be: ServerSocketChannel ssc = ServerSocketChannel.open(); and the compiler didn't warn.

    molavec wrote:
    ServerSocketChannel ssc = ServerSocketChannel.open(); //<--I have never thought do that!! Anyway, how it is static method may work.
    The static method creates an instance of a class which extends ServerSocketChannel, but is actually another non-abstract class.I thought that, but reading the documentation I saw that about open() method:
    Opens a server-socket channel.
    The new channel is created by invoking the openServerSocketChannel method of the system-wide default SelectorProvider object.
    The new channel's socket is initially unbound; it must be bound to a specific address via one of its socket's bind methods before connections can be accepted.
    ...and the problem is the same openServerSocketChannel is abstract, so i don't understand how it could return a ServerSocketChannel.There is a concrete implementation class that has implemented that method.
    I guess that really the open() method use a SelectorProvider's subclase but it doesn't appear in the doc.It doesn't need to. First, you don't care about those implementation details, and second, you know that if the class is abstract, it must use some concrete subclass.
    Ok, I speak Spanish by default (<-- this sounds like "I am a machine", ^_^' ). So, I didn't know how to say that the method would be {}. Is there a way to say that?? I recommendable for me to know, for the future questions o answers.Not sure what you're saying here. But the other respondent was trying to explain to you the difference between an abstract method and an empty method.
    // abstract method
    public abstract void foo();
    // empty method
    public void bar() {
    Which class does extend ServerSocketChannel? I can not see it.It may be a package-private class or a private nested class. There's no need to document that specific implementation, since you never need to use it directly.

  • Why does the child class need to implement the parent classes constructor?/

    As I was playing around with some code I came across this point :
    First Class
    public class A {
         public int x;
         A(int i){
              x=i;
              System.out.println("A is initialised");
    }Second Class extending it :
    public class B extends A{
         private int y;
       // Why do I need this constructor to call parents constructor?
      // My guess is so that when i make an object of class B referring to class A it should make sense?
         B(int i) {                     
              super(i); 
              y=test;
    public static void main(String args[]){
          A a = new A(1);
          A b = new B(1); make an object of class B referring to class A it should work!!
          B c = new B(2);
          B d =(B) new A(2);  --> gives class cast exception!
    }I am little confused here, Can someone throw more light on it.
    Thanks

    You don't override constructors. However, every class, in it's constructor, must call some constructor from the class it's extending. In most cases this is simply super(). However, if your class does not have a default constructor (i.e. you've declared any other constructor, or the sub class does not have access to it, I.E. you've declared it private) then you must include a call to some other constructor in the super class. The constructor in the subclass does not have to be the same as the super class one, but you do have to invoke a constructor from the super class. I.E.
    class A {
      A(int i) {}
    class B extends A {
      B(String b) {
        super(0);
    }

  • Why does iTunes allow you to play music files that are in the trash?

    I recently was up grading my music library why I got my new mac.  I had 2 I tunes libraries on my computer and checked to see which one I was using and deleted the other music folder.  While the folder was in the trash I played the music to make sure that I would not have a problem...... then I empted the trash.  Problem was that after emptining the trash I could not play the music anymore.  so my question is is there a way to set up a preference to not allow I-tune to not allow access to files in the trash. 

    If an iPod is set to automatically sync from a particular iTunes library, when you connect it to that iTunes library, every song on the iPod exists in the iTunes library.  Therefore, if you want to play a song on the iPod using iTunes on the computer, you can just play that song from the computer's iTunes library, and not the iPod.
    If an iPod is set to load songs manually (by dragging songs to the iPod in iTunes), then the iPod is NOT syncing to a particular iTunes library.  The library on the iPod is separate; songs on the iPod may not be in the computer's iTunes library.  Therefore, you can play songs stored on the iPod using iTunes on computer.
    If your shuffle happens to be 1st or 2nd gen, they work differently from other iPods.   They are always associated with only one iTunes library at a time, so you cannot play songs on the shuffle using iTunes on the computer.
    I was wondering how I could transfer music from my iPod to my library
    You cannot transfer song files from iPod to computer using iTunes (except for songs purchased from the iTunes Store).  However, there are third-party methods and utilities that can transfer song files from iPod to computer.  If you do a Google search on something like "ipod transfer," you should get some links.

  • Why does Mozilla allow virus manufacturers to compromise their browser?

    I've been using Firefox for about a decade now, and I've always preferred it to the built in IE software. However, for the last year (or more) I have suffered more and more issues with your browser than ever before (being redirected from trusted pages to BS like www.updateselfnet.com, virus installers launching any user input, Flash player failures 3/4 times I try to watch a video).
    It seems to me that mozilla is okay with providing a compromised browser, and I can only assume that being paid by internet companies to help push their malware or advertising software is more important than providing a "safe browsing experience".
    I'm looking for a browser that works more effectively with actual anti-virus software, and delivers on the user experience that is promised. Maybe an actual pop-up blocker built in would be fantastic (rather than saying it blocks pop-ups, while allowing 75% of them to ruin my day).
    Looking forward to a response. I'm hoping for more than "We promise we don't allow 3rd party organizations to piggyback their unwanted software on our browser, we deny any culpability or responsibility for anything happening to you using our software, thanks for the support".
    -C

    hello CDinsectionP, your assumption that mozilla would somehow profit financially from crapware hijacking the browser is just wrong.
    once you have malware running locally on your machine it's pretty much game over, such software can alter the behaviour of any program and your operating system. a browser is not build to defend against that - it should contain safeguards against vulnerabilities that can be exploited remotely though, so you can't be infected by just browsing a malicious website.
    what you should do if your firefox is affected by adware/malware are the following steps:
    # [[Reset Firefox – easily fix most problems|reset firefox]] (this will keep your bookmarks and passwords)
    # afterwards go to the firefox menu ≡ > addons > extensions and in case there are still extensions listed there, disable them.
    # run a full scan of your system with different security tools like the [http://www.malwarebytes.org/products/malwarebytes_free free version of malwarebytes] and [http://www.bleepingcomputer.com/download/adwcleaner/ adwcleaner] that are specialised in browser hijackers and to make sure that adware isn't present in other places of your system as well.
    [[Troubleshoot Firefox issues caused by malware]]

  • Why does my photos change after importing them?

    I've shot hundreds of pictures from a wedding in sunny Toscana, Italy with a new Sony Hybrid Camera. They're all shot in RAW and looks good in the camera preview. When I import the pictures to Aperture, they look the same in the "filmstrip":
    But then, after selecting them, they change into extremely overexposed versions that can't be used.
    I don't get the same issue when I open them with Photoshop. What is going on?

    Toning this down to half helped a lot. But now it looks kind of gray.
    By default the settings should be o.k. Leave the "hue" boost at a higher value.
    It's a pity, that your first encounter with Aperture is this bad.
    Then you have to do all sort of tweaks and tuning to get them back in decent shape.
    Is this your first encounter with RAW images as well?  RAW photos will generally need a lot of tweaking, since the RAW format is the naked data right of the sensor, without any effects and adjustments applied. RAW is the image format for those photographers that want to develope and tweak the digital negative themselves. If you are happy with the RAW developement that your camera does, consider to set the camera to shoot high quality JPEGS or TIFF images. Then you will have the RAW developement of the camera as the starting point for your own tweaking and do not need to start from point zero and do the basic adjustments as well.

  • Why does my dialog class not work!

    see code below, it shows up as a box with 0 size (just the title bar) it is resizable but is empty. Can anyone explain why!
    code below -
    public class AboutDialog extends java.awt.Frame
    implements ActionListener
    public AboutDialog(Frame parent)
    //super(parent, "AboutDialog...", true);
    setSize(450,350);
    Point p = parent.getLocationOnScreen();
    setLocation(p.x+50, p.y+50);
    //Container pane = getContentPane();
    Container pane = new Container();
    pane.setLayout(new BorderLayout());
    Panel ps = new Panel();
    Button okButton = new Button("Ok");
    okButton.addActionListener(this);
    ps.add(okButton);
    String about = "Write anything you want here";
    //pane.add(ps, "South");
    pane.add(ps);
    TextArea ta = new TextArea(about);
    ta.setFont(new Font("Courier", Font.PLAIN, 12));
    ScrollPane sp = new ScrollPane();
    sp.add(ta);
    pane.add(sp);
    add(pane);
    public void actionPerformed(ActionEvent e)
    setVisible(false);

    Still having trouble eh? I reworked it slightly, and this works for me.
    import java.awt.event.*;
    import java.awt.*;
    class AboutFrame extends Frame implements ActionListener
        public AboutFrame()
            this("AboutFrame... Title you want");
        public AboutFrame(String title)
            super(title);
            setSize(450,350);
            setLocation(50, 50);
            // you'll also need a window listener, because (apparently) awt
            // doesn't support the default close operation, like good ol' Swing
            addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent e)
                    setVisible(false);
            setLayout(new BorderLayout());
            // I originally added the button to a Panel first
            // because if I added the button directly to the
            // borderLayout, it puffed up to fill the space
            // and looked ugly.
            Panel ps = new Panel();
            Button okButton = new Button("Ok");
            okButton.addActionListener(this);
            ps.add(okButton);
            add(ps, "South");
            String about = "Write anything you want here";
            TextArea ta = new TextArea(about);
            // You probably don't need this, I just wanted
            // a mono-spaced font.
            //ta.setFont(new Font("Courier", Font.PLAIN, 12));
            ScrollPane sp = new ScrollPane();
            sp.add(ta);
            add(sp, "Center");
        public void actionPerformed(ActionEvent e)
            setVisible(false);
        public static void main(String[] args)
            new AboutFrame().setVisible(true);
    } Hope this one works for you,
    Radish21

  • Reader 8.1.2 does not allow reading PDF within Web browser???

    Adobe updated my perfectly working reader with version 8.1.2, then I received the following message:
    "Cannot use Adobe Reader to view PDF in your Web browser. Reader will now exit. Please exit your browser and try again."
    I un-installed 8.1.2 and cleaned up the registry.
    Re-installed 7.0.9 and finally I am back in business.
    Now Adobe insists in wanting to install 8.1.1 AND IS CONSTANTLY placing a pop up to offer me the new version WHICH DOES NOT WORK!
    How do I get that popup to go away?
    Thanks.

    I believe that I found a fix for this by going into 'My Computer'>Tools>Folder Options>File Types, where I changed the 'destination' file used to open PDF files from the older Adobe that was listed to the most recently installed version (8.1.2) (which is AcroRd32.exe, not simply AcroRd.exe). This change now shows up when I'm opening a downloaded PDF file; the automatic program to do so is now indicated as the newly installed Adobe 8.1.2 (i.e. AcroRd32.exe). My other PDF files are now opening automatically as well.

  • Why does turning off auto updates turn them on?

    I have been trying to stop the auto update of Flash player for months - even went so far as to totally uninstall, remove all traces, then install fresh with the "do not auto update" setting. It still gives me pop-ups. Browsing the 'net I saw an article that made me think it might be related to Shockwave. Shockwave has NEVER asked me to update but, silly me, I unchecked it anyway.
    And now it is on and attempting to auto update.
    So, I'm left with two products that will not obey their settings.
    Please advise.

    i MonH,
    Unless someone deleted the file, it should exist on your system.  If you're on a 32-bit OS, the file will be in C:\Windows\System32\Macromed\Flash.  If you're on a 64-bit OS, the file will be in C:\Windows\SysWOW64\Macromed\Flash.  You can edit the file manually, or edit the update settings in the Flash Player Settings Manager, which may be easier. 
    To launch the Settings Manager, either navigate to the Control Panel and select the Flash Player icon, or launch a non-Chrome browser and view Flash content, then right-click on the content to display the Flash Player context menu.  Select Global Settings.
    When the Settings Manager displays, navigate to the Advanced tab.
    Click the Change Update Settings button
    Select the Never check for updates (not recommended) radio button
    Your update option has been set
    Viewing the mms.cfg file after making the updates, it should contain the following:
         AutoUpdateDisable=1
         SilentAutoUpdateEnable=0
    AutoUpdateDisable=1 is what disables the updates (background and notification) completely.
    Note that whenever you uninstall Flash Player the update settings are reset to the default setting (AutoUpdateDisable=0).  You'll need to be sure to select Never check for updates (not recommended) when you install Flash Player again.
    Maria

  • Why does scrolling up in bookmarks cause them to be underlined?

    When I drag my cursor UP the bookmarks list pane the bookmarks that are covered by the cursor travel become underlined. When I scroll DOWN the underlining is removed. It doesn't seem to do anything, but looks like a bug.

    run this script in terminal. It will reset to the default (it funtions like the reset homepage layout funtion in IOS)
    rm ~/Library/Application\ Support/Dock/*.db

Maybe you are looking for

  • Itunes won't recognize iPod after installing MediaMonkey..

    Hi, I recently switched from Itunes to MediaMonkey, and I'm very happy. But my girlfriend still uses iTunes. And now her iTunes won't recognize neither her or my iPod when I connect either of them. Windows and MediaMonkey recognizes them perfectly. i

  • Clone  in same machine cold/hot

    Hi, 1,What are the things i have to consider before start the cloning(both cold,hot). 2,please anyone provide steps for that. 3,Is the listener should be started before starting the procedure in target machine? 4,I am planned to do in same machine or

  • How do I create a catalog in elements organizer?

    How do I create a catalog in elements organizer.  I keep getting the error message Catalog could not be opened, an internal programming error has occurred.

  • Installing my Illustrator CS4

    Hi, I have just bought a new MacBook Pro and when I try to install my Illustrator CS4 the installer refuses to let me type in my serial number and I'm obliged to opt for a trial period. Why am I having this problem?

  • Laptop to internet ok. Iphone to internet "connection to server failed"

    Laptop to internet ok. Iphone to internet "connection to internet failed" can someone help me fix this?