Why only public methods in interfaces?

Howdy all,
I'm wondering if someone can shed some light on why Java doesn't allow interfaces to declare non-public methods.
Ideally, I'd like to do something like this:
public Interface Foo {
  protected void setFooProperty(int);
  public int getFooProperty();
public Interface Goo {
  protected void makeGooey(boolean);
  public boolean isGooey();
public class A implements Foo
public class B implements Goo
public class C implements Foo, GooI don't see any technical reason why interfaces must be restricted to declaring public methods only, but it seems too arbitrary to have been done without reason. Any ideas?

I don't think that is a good idea to put non-public methods in public interfaces. But I beleive that's a good idea to have protected (or friendly) interfaces to be used only in package scope. It could help a lot some projets defining a second level of data exposure of an object so that developers of that package could have more information that others users from outside the package have that are interesting to develop better algorithm that work with that data. In this way, we can defien thre levels of that access: The lower is the package user, that can see the minimum that's possible, above him we have the package developer that don't work directly with the data, but needs some deep access to it to do cool stuff, and finally we have the guy that is doing the object that deals directly with the data (and encapsulate it).
In this way we can decouple a little the data from the algorithms that work on it, put between them an interface that standarize the access to the data in an intermediate level.
Hope you are able to understand what I wrote (my english isn't so good!).
RGB

Similar Messages

  • Why all the methods in interface should be implemented

    why all the methods in interface should be implemented

    Because you'll break the contract saying "this instance features all methods defined in that interface" otherwise.
    In other words, as long as an interface isn't completely implemented by an instance, it's not validly implemented at all.

  • Non-public methods in interface ??

    Is this possible? Or must all methods (signatures) in an interface be public?
    And would that mean that I cannot change the visibility modifier in implementing classes as this restricts the visibility by inheritance, which I believe is prohibited...
    Thanks for any answer,
    AC

    Everything in an interface must be public. However, the interface itself doesn't have to be.
    Yes that means that all implementing classes must have public implementing methods.
    However, proxies, adapters and decorators will get you out of serious design problems if you bump into any.
    Hope this helps.

  • Why create public methods?

    Hi all,
    When I declare a class as default ( i mean that no access specifier is declared), why do i need to declare its member functions as public for them to be accessible by other classes in the same package?
    Thanks in advance,
    Seshu.

    You don't need to make methods public for them to be accessible by other classes in the same package. Why do you think you have to?
    Also, the access specifier of methods doesn't have anything to do with the access specifier of the class.
    Jesper

  • Public methods with package-only access?!

    Hello,
    I've just encountered the following problem:
    I was trying to invoke a method from the interface java.util.List via reflection on an instanceo obtained via java.util.Arrays.asList(Object[] array).
    Although this method is public (since is is declared in a public interface), the invocation failed with an IllegalAccessException.
    I guess the reckoning behind this is that the entire class has package protected access, thus you may not access any member reflectively outside its package.
    Does this really make sense? Is there a way to circumvent this behaviour?
    Any thoughts appreciated!

    I doubt your assumption (package protected) because
    asList simple returns an ArrayList. And if in an
    interface a method is declared you cannot reduce it's
    visibilty in an implementing class.Yes, the methods are all declared public, but the entire class (java.util.Arrays.ArrayList) is package-protected.
    But still, it's strange: you can obtein the method using, for instance, Arrays.asList(new Object[]{"hallo"})getClass().getMethod("size", null), but you cannot invoke it! Ironically, the error message of the IllegalAccessException says "cannot access member with modifiers public"...
    >
    But you can set the method accesible for reflection
    calls through:
    Method.setAccessible(true)
    Ah, thanks, now it works!
    But isn't that kinda dirty? If there was a Security Manager present, it would immediately fail, wouldn't it?
    I'd still like to understand why you cannot simply invoke a public method of a package-protected class!

  • Why do we need Serializable Interface since there is no method decl. inside

    On working with Serialization in java
    I could see that the Serializable Interface is empty without any method inside.
    Also, the writeObject() and readObject() accepts only if the Serializable interface is implemented to a class.
    What is the use of implementing an empty Interface?
    Please clarify.
    Thanks in advance.
    Regards,
    R.Mahendra Babu

    The completely empty Serializable is only a marker interface -- it simply allows the serialization mechanism to verify that the class is able to be persisted.

  • Why is it that the interfaces cannot have static methods?

    why is it that the interfaces cannot have static methods?

    Interfaces contain polymorphic methods. Static methods are not polymorphic, and therefore would not make any sense to be in interfaces.

  • Static methods in interfaces

    Java cognoscenti,
    Anyone know why I can't declare a method as static in an interface, but I can in an abstract class. Surely, semantically it's the same - defering the implementation of a static method, not an abstract class and an interface. By the way, I'm using JDK 1.2.2 if that makes a difference

    No, it's not the same. You are not "defering the
    implementation of a static method" because static
    methods are never polymorphic.
    Static methods cannot be abstract for this reason, and
    only abstract methods are allowed in interfaces.I didnt't know that. I thought that - because you can override static methods and you can call them onto an actual instance the method binding would be done at run-time, not at compile-time. So I was trying to prove you wrong, but you are correct !
    A short summary of what I've learnt so far:
    - interfaces cannot contain static methods
    - abstract classes cannot contain abstract static methods
    - static methods can be overriden, but they are not polymorphic; this means that the compiler decides which method to call at compile-time.
    /* output
    SuperClass.someMethod()
    SubClass.someMethod()
    SuperClass.someMethod()
    SuperClass.someMethod()
    SubClass.someMethod()
    SubClass.someMethod()
    SuperClass.someMethod()
    public class Test {
      public final static void main(String[] args) {
          // output: SuperClass.someMethod()
          new SuperClass().someMethod();
          // output: SubClass.someMethod()
          new SubClass().someMethod();
          // output: 2x SuperClass.someMethod()
          SuperClass someClass1 = new SubClass();
          someClass1.someMethod();
          showSuper(someClass1);
          // output: 2x SubClass.someMethod()
          SubClass someClass2 = new SubClass();
          someClass2.someMethod();
          showSub(someClass2);
          showSuper(someClass2); // SuperClass.someMethod()
      public final static void showSuper(SuperClass c) {
            c.someMethod();
      public final static void showSub(SubClass c) {
            c.someMethod();
    class SuperClass {
      public static void someMethod() {
        System.out.println("SuperClass.someMethod()");
    class SubClass extends SuperClass {
      public static void someMethod() {
        System.out.println("SubClass.someMethod()");

  • Protected Methods in Interfaces

    Why don't interfaces allow you to declare protected methods? Is there a way around this?
    The reason I ask involves a current project of mine. I have an inheritance hierarchy including an abstract Event base class with many concrete derived Events. I want to define many protected methods in the base Event class, which all my derived Events will use, in order to save me a lot of coding. I'm also trying to make my program reusable, and isolate the protocol changes to this Event hierarchy and a Packet hierarchy as well. For both these hierarchies, I want to implement interfaces that make sure that the programmer defines these necessary, protected methods. Yet I cannot declare protected methods in my interfaces!

    > I have this same desire: to have protected
    methods within interfaces.
    Interfaces are not intended to (nor can they) provide
    implementation.Yes, this is clear. Yet they "promise" an implementation. In the Java interface model, they only promise the public interface. I have yet to see why they cannot promise protected methods. I'm not really interested in code inheritance (reusing the code). I'm interested in what is called interface inheritance to achieve certain polymorphic goals.
    >
    > any design patterns that can be used to get
    around this problem.
    I'd suggest using composition rather than
    inheritance. Let me know if I should explain
    further.
    Yes, I understand about composition (or delegation) as a way to "inherit" the functionality; however, I want to treat the subclasses polymorphically. I'm designing class library/frameworks that require a certain level of structure. The subclasses need to maintain the encapsulation provided by protected methods. I don't want external clients calling the protected methods, but the only way to achieve multiple (interface) inheritance is through Java's public interfaces, which then exposes the methods. I see no way around this problem. I'm not familar with the technical challenges of implementing multiple inheritance within compilers etc. At first glance, I don't see why allowing methods to be declared protected within the Java interface construct would cause serious technical problems.
    ~
    P.S. Yes, this is an old thread...
    Sorry, yes this is an old thread. I did some searching on this topic and this thread came up. Thanks for your reply.

  • Limiting access to public methods

    Hi!
    I'm just curious if there's a way to do this.
    You see, I have a package that is supposed to read an xml file, and through public methods give out data from that file.
    Now, in order to do this, I implement a SAXHandler. But the SAXHandler needs to have public methods like startElement, etc.
    Now let's say I'm one of those anally retentive information-hiding people. I really wouldn't want those public methods to be available to ust anyone who uses my class. And I can't make them protected, because the interface says they can't be, and anyway - there's no simple way to put the SAXParser in my package
    While this example is specific, the problem seems a general one.
    What do you do when: an interface calls for public methods, but you don't want just anyone to get to those public methods. (the only one you want to allow is the one that made you implement the interface in the first place).
    Any hints? Thanks!
    /Z

    thanks for the hint's everyone! Your thoughts were along the lines of my own. Hiding the implementing class inside another class is probably my best bet.
    I doubt I'll do it though - I guess I'm just not that anal... yet...;-)
    I guess what I was thinking was that maybe there was some way around the necessity of wrapping the implementor, because that just seems ugly in a lot of cases and Java been so good at getting rid of ugly since Tiger IMHO.

  • Instance Dependent Public Method is not working for Workflow

    Hello Experts,
    I have made Custom class for  a workflow. This class is triggering the WF fine but the problem is while trying to execute a WF task which contains a Instance Dependent & Public  method its not working , the WF task is not processing though I'm passing the instance of the class  properly from WF to WF task . When I'm changing the method to Static & Public then the workitem is executing perfectly. Can you please help & suggest the way to find the problem ?
    Thanks & Regards ,
    Jeet

    Are you absolutely sure that you have the instance of the object in the workflow container? Open the technical log the see if the object instance is there - or is the container element initial (or "not set")?
    yes it is instantiated properly no error over there.
    What about if you test the method directly in SE24 (as an instance method)? Is it working then? If you can make it work in SE24 as an instance method and you are sure that the instance exists in the workflow,
    I have checked the class in a stand alone run in this case also it runs fine as before.
    The obvious question of course is that have you implemented the IF_WORKFLOW interface methods (the two first ones).
    it is coded like below
    BI_PERSISTENT~FIND_BY_LPOR
      create object result
          type
            (lpor-typeid)
          exporting
            ip_key = lpor-instid.
    CONSTRUCTOR
       me->m_KEY    = ip_key.
       me->m_por-catid = 'CL'.
       me->m_por-typeid = CL_ZZZ'.
       me->m_por-instid = me->m_key
    BI_PERSISTENT~LPOR
    result =  me->m_por.
    Main confusion is Method is working only if declared STATIC & PUBLIC  but not for the INSTANCE DEPENDENT & PUBLIC.

  • RMI only accpets on Server Interface

    Hi guys...
    Well I have a program which 2 interfaces were bind to RMI server, StockServer and PurchaseServer.
    The StockServer are works perfectly, but the PurchaseServer not, both interfaces are binding without exceptions, both stub are generated and referenced at runtime without exceptions - I print both stub with the toString method and a non-null value are printed.
    But when I try to invoke a remote method from PurchaseServer interface I catch a Connection refused to host 127.0.0.1 as a java.rmi.ConnectException
    I know which the RMI server support more than one interfaces at the same time, but why only the first one are work properly?!!??
    Thanks all. Its URGENTE!!!!!!

    HI josAH,
    Thanks for the help, but I am using only one rmiregistry server and two server interfaces to bind into it. right now I solve the problem, I mount a list of client ot try send message to the server and all of them works properly...
    So I focus on my application and get a reference problem, one of my stub clients was trying to connect to the remote interface before it been completly started. Multithread hard code problems
    Thanks all.

  • Lint Tool to detect unused public methods?

    I'm looking for a java lint tool that will point out <b>public</b> methods that
    are unused within my codebase. All of the tools I've reviewed to date
    have only detected unused private methods. Does such a tool exist?
    If so, can you point me in the right direction?

    I don't think such a tool can exist, because the tool wouldn't know whether your writing an API or an end user application.
    Also, in any program you might end up with public methods that do nothing, but need to be there to complete an interface implementation.
    Presumably, the goal with finding the unused public methods is to remove them and to improve performance somehow. I don't think this is a worthwhile exercise as the compiler does a pretty good job of this optimisation already.

  • Public methods/fields

    What would be wrong with making all my fields, classes, methods, ect public. How would people be able to tamper from outside with them.

    Another reason to make variables private is to separate the interface of your class from the internal implementation. A simple example of this is a class to represent a complex number (a + bi). You would have some public methods for manipulating the complex number, but you would want the actual representation of the complex number to be internal and private. Why? Because at some later time, you might want to change the internal representation, for performance reasons, or to exploit some new feature, etc.
    If you had all public variables and public methods, there would be nothing you could change without requiring the users of your class to rewrite their code, which, after all, depended on all the public variables you had in it.
    If, on the other hand, you had the internal representation hidden with private variables and methods, the change in implementation would be no problem and users could use your new improved class without rewriting their code.
    That's one of the main benefits of OOP; being able to wall off your internal implementation while keeping a viable external interface.

  • Error while calling a super class public method in the subclass constructor

    Hi ,
    I have code like this:
    CLASS gacl_applog DEFINITION ABSTRACT.
      PUBLIC SECTION.
        METHODS:
                create_new_a
                   IMPORTING  pf_obj       TYPE balobj_d
                              pf_subobj    TYPE balsubobj
                              pf_extnumber TYPE string
                   EXPORTING  pfx_log_hndl TYPE balloghndl
                   EXCEPTIONS error
    ENDCLASS.
    CLASS gacl_applog IMPLEMENTATION.
      METHOD create_new_a.
        DATA: ls_log TYPE bal_s_log.
      Header aufsetzen
        MOVE pf_extnumber TO ls_log-extnumber.
        ls_log-object     = pf_obj.
        ls_log-subobject  = pf_subobj.
        ls_log-aluser     = sy-uname.
        ls_log-alprog     = sy-repid.
        ls_log-aldate     = sy-datum.
        ls_log-altime     = sy-uzeit.
        ls_log-aldate_del = ls_log-aldate + 1.
        CALL FUNCTION 'BAL_LOG_CREATE'
             EXPORTING
                  i_s_log      = ls_log
             IMPORTING
                  e_log_handle = pfx_log_hndl
             EXCEPTIONS
                  OTHERS       = 1.
        IF ( sy-subrc NE 0 ).
          MESSAGE ID      sy-msgid TYPE sy-msgty NUMBER sy-msgno
                  WITH    sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
                  RAISING error.
        ENDIF.
      ENDMETHOD.
    CLASS gcl_applog_temp DEFINITION INHERITING FROM gacl_applog.
      PUBLIC SECTION.
        DATA: log_hndl   TYPE balloghndl READ-ONLY
            , t_log_hndl TYPE bal_t_logh READ-ONLY
        METHODS: constructor
                   IMPORTING  pf_obj       TYPE balobj_d
                              pf_subobj    TYPE balsubobj
                              pf_extnumber TYPE string
                   EXCEPTIONS error
               , msg_add      REDEFINITION
               , display      REDEFINITION
    ENDCLASS.
    CLASS gcl_applog_temp IMPLEMENTATION.
      METHOD constructor.
        CALL METHOD create_new_a
               EXPORTING  pf_obj       = pf_obj
                          pf_subobj    = pf_subobj
                          pf_extnumber = pf_extnumber
               IMPORTING  pfx_log_hndl = log_hndl.
        IF ( sy-subrc NE 0 ).
          MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
                  WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4
                  RAISING error.
        ENDIF.
      ENDMETHOD.
    A public method of Super class has been called from the constructor of the sub class. we are getting the syntax error :
    ' In the constructor method, you can only access instance attributes, instance methods, or "ME" after calling the constructor of the superclass…'
    Can you please suggest how to change the code with out affecting the functioanlity.
    Thank you ,
    Lakshmi.

    Hi,
    Call that method by instance of Subclass.   OR
    SUPER-->method.
    Read very useful document
    Constructors
    Constructors are special methods that cannot be called using CALL METHOD. Instead, they are called automatically by the system to set the starting state of a new object or class. There are two types of constructors - instance constructors and static constructors. Constructors are methods with a predefined name. To use them, you must declare them explicitly in the class.
    The instance constructor of a class is the predefined instance method CONSTRUCTOR. You declare it in the public section as follows:
    METHODS CONSTRUCTOR
            IMPORTING.. [VALUE(]<ii>[)] TYPE type [OPTIONAL]..
            EXCEPTIONS.. <ei>.
    and implement it in the implementation section like any other method. The system calls the instance constructor once for each instance of the class, directly after the object has been created in the CREATE OBJECT statement. You can pass the input parameters of the instance constructor and handle its exceptions using the EXPORTING and EXCEPTIONS additions in the CREATE OBJECT statement.
    The static constructor of a class is the predefined static method CLASS_CONSTRUCTOR. You declare it in the public section as follows:
    CLASS-METHODS CLASS_CONSTRUCTOR.
    and implement it in the implementation section like any other method. The static constructor has no parameters. The system calls the static constructor once for each class, before the class is accessed for the first time. The static constructor cannot therefore access the components of its own class.
    Pls. reward if useful....

Maybe you are looking for

  • How do i save an audio file using quick time?

    How do i save a audio file from quick time. When I looked it up I was told to go to file on quick time and click on save as but my quick time has no save as to click on in file. What Now?

  • Mac mini and existing Airport wireless connections

    Hi. If i purchase the new mac mini duo processor...I can supposedly hook it up to my old iMac and run Tiger on it...correct? I am using Airport extreme to connect wirelessly to the iMac, the iBook and my Powerbook. Which Airport would I use then for

  • Need help with Acrobat 6.0 pro; size of print is stuck @ 4.6"- can't change file print size

    - can't change file print size at all. printing one size dont know how to change it  (looking in print preview while in acrobat 6.0 pro..   MAC OS  10.5.8

  • Thread waiting for monitor - appending to previous post

    04:25:51,721 ERROR [ExecuteThread: '55' for queue: 'weblogic.kernel.Default'] com.documentum.web.common.Trace - SessionSynch@bc53ac[lockCount=2,lockOwner=Thread[ExecuteThread: '54' for queue: 'weblogic.kernel.Default',5,Thread Group for Queue: 'weblo

  • Large number display problem

    I get an number from my db column (SQL2000), and I need to display a accumulative sum of that column. I am now facing a problem of the automatic convertion of the sum when it is greater than 9999999. For example, when the sum is now 12345678 it will