This is some information on the Java 6 certification that I prepare. This information is not very well structured and it is most of the time an answer to the questions that come when I read the SCJP 6 book (Bates and Sierra). *** AS OF 5 OF MARCH 2010, I AM SCJP 6.0 ***

Thursday, January 7, 2010

6 - visibility of interfaces and classes

A java interface can be public or not ! If you use an ide please notice that netbeans will by default make your interface public.
Sound interesting for me. Why ?

Because the methods you define in an interface are by default public and abstract and you cannot change this.
So if you implement the interface, you have to make the methods public ! You cannot do anything againts that fact ! 
If you implement the interface then the methods must be public !
Let's go back to the definition of the interface. If the interface is NOT public it means it has to be used in the same package than the class that will implement the interface ! And of course the methods have to be public and all the packages can use the methods. So even if we cannot change the method signature (must be public). Is it possible to make the method package ? The only way I found is to make the class package... In other words to remove the public from the class definition. This time even if the method is defined public (must be I repeat) the class definition (not public) will prevent to use it outside of the package ! So it seems impossible to use an interface and to make the methods private... I suppose it is related to the definition of an interface in UML that has to be public... Functionality to be accessed by all the packages !  Or in java make the interface and the class not public !



Example 1 - the interface is NOT PUBLIC :






package pkg2;

interface Int1 {

    public abstract void openFileNotPublic() throws java.io.FileNotFoundException; // is by def public and abstract !!!

}



package pkg2;

class Class1 implements Int1 {

    public void openFileNotPublic() { // must be public
        System.out.println("openFileNotPublic");
    }
}






package pkg2;

public class Main {

    public static void main(String[] args) {
        new Class1().openFileNotPublic();
    }

}




Example 2 - the interface is PUBLIC :





package pkg2;

public interface Int1 {

    public abstract void openFileNotPublic() throws java.io.FileNotFoundException;

}


package pkg1;

public class Class1 implements pkg2.Int1 {

    public void openFileNotPublic() {
        System.out.println("openFileNotPublic");
    }
}

package javaapplication19;

public class Main {

    public static void main(String[] args) {
        new pkg1.Class1().openFileNotPublic(); // we reused the method from the 1st example and it should be this time openFilePublic to be consistent !
    }

}

That's all folks !
-Rudy-



1 comment:

  1. Could you notice that your are not forced to throw the Exception even if the interface declares to throw it...

    ReplyDelete

Followers