Static Interface Pattern

Summary
=======
Define an interface which declares static methods.
The essence of what I mean by this is: define a number of classes which contain/provide access to common methods to which we can make static calls.
Details
=======
What we are trying to achieve here is effectively an interface which garuantees us that the classes of a particular type (with a common parent class/interface) will all contain a specific method to which we have static access.
Simple example
==============
Here we have two classes that implement the Animal interface (Dog and Cat). Each class supplies a static method getType() which returns some non-instance-specific information (this method is static because the type is the same for all instances of the given class. E.g. ALL Dogs are of type 'Doggy').
interface Animal
class Dog implements Animal
    public static String getType()
        return "Doggy";
class Cat implements Animal
    public static String getType()
        return "Kitty";
}The problem is: How can we garuantee a client application that all Animals will supply (in some way) this static method.
[In this particular example the methods differ only in the information they return, but the solution should allow the implementation of these methods to differ too].
Thanks for your thoughts.
JohnSenford [@hotmail.com]

interface Animal
class Dog implements Animal
     public static final String getType = "Doggy";
//    public static String getType()
//        return "Doggy";
class Cat implements Animal
      public static final String getType = "Kitty";
//    public static String getType()
//        return "Kitty";
or maybe an abstract base class;

Similar Messages

  • Static interface Vs Static nested interface declaration

    Hi,
    I have observed that static interface declaration is not allowed in Java. However static nested interface declaration is allowed.
    I could not understood reason behind this behavior.
    e.g.
    interface A{
         void AA();
         public static abstract interface Aa{
    } ........... this is allowed in Java.
    static interface d{
    } ...... This is not allowed in Java...
    I already know that static mean one for class and interface has only abstract method.
    Please let me know if any one know resign behind this.
    Thanks .

    Why don't you go to a Java forum?

  • Interface Pattern "Stateful"

    Hi,
    I was wondering about the interface pattern "stateful" that is available in ESR of PI 7.1. I already read all the information in [this|Re: Query in PI7.1 Service Interface] post but still don't know when to use it? Can anyone maybe give an example on when to use this interface pattern instead of for example the TU&C/C pattern?
    In all the information given it always says that stateful can either be provided by the messaging runtime or not. Which runtimes do support this? Integration Engine, local WS-Runtime? And if so starting with which version are they supported?
    Thanks a lot,
    Manfred

    Very good description was found here: https://ecohub.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/b0f371e9-18d0-2b10-bbb4-ecc935ddb732.

  • Static interfaces

    Hi everybody,
    I could not find eny information about static interfaces (not static members of an interfaces - static interfaces itself).
    Could anybody give me some information about it ?
    I came accross with many interfaces wich are declared as:
    public static interface name_of_interface
    Thank you for all the answers.
    Adrian

    Inner interfaces can be declared static.Well, there you go. I should Google myself before answering!
    Never thought of inner interfaces.
    Cheers!

  • 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.

  • Using static interface inner class.. how?

    Can anyone tell me how I'm able to use an inner class that is a static interface?
    Specifically I'm getting DocumentEvents through a DocumentListener..
    Then within DocumentEvents there is an inner class which is a static interface called:
    DocumentEvent.ElementChange, I'm trying to use the methods contained within the interface ElementChange.
    Can anyone throw a helping hand as to how I go about this?
    Thanks :)

    public class A ... {
    public static interface B {
    }Just creates a public interface called A.B
    How are you supposed to use this with your DocumentEvent? I can't say

  • Static Interface Fields

    public interface interface {
         static public field = 1;
         public void methods();
    when is this correct to use in the OOP/Software Pattern paradigm?
    I thought interfaces were only there to define behaviors (i.e. methods)
    What are static fields doing here?
    Why are static methods not allowed in interfaces while static fields are?
    Thanks

    public interface interface {
         static public field = 1;
         public void methods();
    }Indded it should be public static final (i.e., constants). The compiler supports not specifying final, and adds it automatically, but one should make that explicit.
    when is this correct to use in the OOP/Software
    Pattern paradigm?Unlike the previous posters, I don't find that bad against OO principle.
    If a constant is logically related to the capabilities defined by an interface, it's not a bad thing in itself to declare the constants in the interface's namespace.
    public interface HairDressable {
      public static final int BLONDE = 0;
      public static final int RED = 2;
      public static final int BLACK = 3;
      public void haveHairCut();
      public void haveColorChanged(int newColor);
      public int getHairColor();
    }All classes implementing the interface automaticaly see the constant, and can refer to it without prefixing by the interface name. public class PomPomGirl implements HairDressable {
      public void haveColorChanged(int newColor) {
        if (this.favoriteTeam.getName().equals("Red Socks") && (newColor!=RED)) {...}
    }Any class not implementing the interface can also refer to the constant, by prefixing with the interface's name, as in public class RedTeamFanClub {
    public void makeUp(PomPomGirl pomPomGirl) {
        pomPomGirl.haveColorChanged(HairDressable.RED);
    } What IS bad is to have a class implement the interface only for the sake of referring to the variable without prefixing, like public class HairDresser implements HairDressable {
      public void handleFancyLady(Bimbo bimbo) {
        bimbo.changeColor(RED);
      // Dummy implementation of method that should belong here
      public void haveHairCut() {}
      public void haveColorChanged(int  c) {}
      public int getHairColor() {return BLACK;}
    I thought interfaces were only there to define
    behaviors (i.e. methods) I would say "to advertise capabilities".
    Here both changing the color and getting the current color are capabilities that involve a notion of color that is common to all HairDressable implementing classes. I deem defining this notion in the interface itself makes sense.
    (OK, defining this notion as a bunch of int constants is not very well engineered, but let's keep the discussion focused).
    Now there's the pragmatic approach too : if you define constants in your interface, you run the risk that a bad programmers will someday implement the interface only to lazily refer to the constant.
    But you run that risk with abstract classes too - yes, I've seen that!
    Why are static methods not allowed in interfaces while
    static fields are?Only static final fields, which makes a difference.
    Static methods don't advertise the capabilites of an object. And they can't be overridden.
    Neither does a constant, in itself, but there's a point in defining the constant in the scope where it makes the most logical sense.
    For completeness, note there's an RFE on the BugParade to add statis methods to interfaces (http://developer.java.sun.com/developer/bugParade/bugs/4093687.html).
    As I understand it, and although I don't support it, I think there's a point in defining a static method and its implementation in an interface, so as to, in the same vein as for the constants, put in the interface's scope a method whose implementation logically has a meaning for all implementing classes of the interface
    (I'd say such methods are rare enough not to deserve a language change).
    But it seems ugly (and fortunately impossible at that point) to add the notion of "abstract static methods" that an interface could declare and all implementing class would have to implement.

  • Static Interface Methods in ABAP

    Hello,
    I'd like to know what sense it makes to define static methods in an interface.
    My understanding is, that an interface can only be used with an instance of a class implementing that interface. So I always need to have an instance and thus, static methods are not needed.
    But ABAP-OO (in contrast to Java, for example) allows that, so maybe there is some need for that?
    Thanks for your help, best regards,
    Timo Wolf.

    Hi,
    As you know that static methods are not instance- specific. Hence when a class implements an interface, the methods defined as static do not require an instance-specific call. Rather they are called as CLASSNAME=>INTREFACE_NAME~STATIC_METHOD_NAME. You do not need an instance to access them.
    The only purpose of declaring a method as STATIC in interface definition is to create an agreement that a particular method will not depend on an instance to work. When a class implements the interface, calls to this method will be as mentioned above.
    <b>
    As far as the static components of interfaces are concerned, you can only use the interface name to access constants:
    Addressing a constant <const>: <intf>=><const>
    For all other static components of an interface, you can only use object references or the class <class> that implements the interface:
    Addressing a static attribute <attr>: <class>=><intf~attr>
    Calling a static method <meth>: CALL METHOD <class>=><intf~meth>
    </b>
    Hope this helps.
    Regards
    Message was edited by: Shehryar Khan
    Message was edited by: Shehryar Khan

  • Apply static method requirements on class (Static interface methods)?

    I have a set of classes where is class is identified with a unique ID number. So each class has a public static int getId() method. Each class also has either a constructor that takes a byte array or a static factory method that takes a byte array.
    I would like to maintain a hashmap of these classes keyed to the ID's however I am not sure how to have some interface of abstract parent class that requires each of these classes to implement these static methods.
    What I was hoping to do was something like this>>>
         public interface MyClasses{
              static MyClasses createInstance(byte[] data);
         HashMap<Integer, MyClasses> map;
         public void init() {
              map = new HashMap<Integer, MyClasses>();
              map.put(Class1.getId(), Class1.class);
              map.put(Class2.getId(), Class2.class);
         public void createInstance (int id, byte[] data) {
              map.get(id).createInstance(data);
         }Is there some way I could do this?

    What about something like this?
    public interface Initializable
         public void initialize(byte[] data);
    public class Factory
         private final Map<Integer, Initializable> map = new HashMap<Integer, Initializable>();
            public void registerClass(int id, Class klass)
                    if (! Initializable.class.isAssignableFrom(klass))
                             // you may also want to ensure the class declares a parameterless constructor
                             throw new IllegalArgumentException("duff class");
                    if (this.map.keySet().contains(id))
                             throw new IllegalArgumentException("duff id");
              this.map.put(id, klass);
         public Initializable createInstance(int id, byte[] data)
                    // need some exception handling of course
              Initializable i = map.get(id).newInstance();
                    i.initialize(data);
                    return i;
    }

  • Static interface functions

    Hi everyone..
    I have a class Tourist, which implements an interface named GenericUser. The former implements a static function "SF" but i cannot define "SF" as static in the interface. Any ideas? Anyone out there? :)

    Here's how it would be called...
    String retValue = GenericUser.getUserResponse();
    And therein lies the problem. It will try to call GenericUser's getUserResponse, not that of any implementing class. How could it possibly even know which class' method to call with what you've got.
    You might think to try something like this: GenericUser gu = new GenericUserImpl();
    gu.getUserResponse(); But that still won't help. If getUserResponse were non-static, it would call GenericUserImpl's version of that methhod.
    But for satic methods, which class' version is called is determined by the compile-time type of the reference (GenericUser), NOT the runtime type of the object.
    In short: Static methods are not polymorphic. That's just a rule of the Java language.

  • Static interface?

    I'm writing some classes that have only static methods. I would like to have them all implement an interface which has these methods, like so:public class AImpl implements A {
      public static void someMethod() {
        // do something
    public interface A {
      static void someMethod();
    }This isn't allowed. Is there anyway to do something similar? Or is it just not a possibility?
    Thanks in advance,
    m

    This is one of the cases where the benefits of singleton over classes with static methods is vivid. you can turn your class with static methods into a singleton and take benefot of the interfaces you already defined. Here is some simple code to show it,
    public interface A {
    public void methodA();
    //This is the class that had only static methods
    public class Foo implements A{
    private static Foo instance = new Foo();
    private Foo() {}
    public static Foo getInstance() {
    return instance;
    //previously it was a static method
    public void methodA(){
    usage:
    rathern than calling
    Foo.methodA()
    you have to call
    Foo.getInstance().mathodA()
    you can use Foo.getIntance() anywhere where an A object is expected.
    If it is still not clear, feel free to ask.

  • [SOLVED] 2nd static interface is up, but doesn't show an IP address

    I must be missing something basic.  I'm in the process of setting up a simple network configuration in order to test out nftables.  I'm using netctl. I have have 2 ethernet ports.  The first interface, eno1, is connected to a router, and works fine.  The second interface, enp2s0, is connected to a switch (for testing NAT behind the firewall) and can't seem to get an IP address.
            Internet --- router --- eno1 --- [server] --- enp2s0 --- 4-port switch
                                                                                           |
                                                                                     test client
    [root@ibis etc]# cat /etc/netctl/eno1
    Description='A basic static ethernet connection'
    Interface=eno1
    Connection=ethernet
    IP=static
    Address=('192.168.1.5/24')
    #Routes=('192.168.0.0/24 via 192.168.1.2')
    Gateway='192.168.1.1'
    DNS=('192.168.1.1')
    [root@ibis etc]# cat /etc/netctl/enp2s0
    Description='A basic static ethernet connection'
    Interface=enp2s0
    Connection=ethernet
    IP=static
    Address=('172.18.90.1/24')
    #Routes=('192.168.0.0/24 via 192.168.1.2')
    Gateway='192.168.1.5'
    DNS=('192.168.1.1')
    When I try and bring the 2nd interface up I get an error message:
    [root@ibis etc]# netctl start enp2s0
    Job for [email protected] failed. See 'systemctl status [email protected]' and 'journalctl -xn' for details.
    [root@ibis etc]# systemctl status [email protected] -l
    â [email protected] - A basic static ethernet connection
    Loaded: loaded (/etc/systemd/system/[email protected]; enabled)
    Active: failed (Result: exit-code) since Wed 2014-06-04 08:47:36 CDT; 12s ago
    Docs: man:netctl.profile(5)
    Process: 742 ExecStart=/usr/lib/network/network start %I (code=exited, status=1/FAILURE)
    Main PID: 742 (code=exited, status=1/FAILURE)
    Jun 04 08:47:36 ibis network[742]: Starting network profile 'enp2s0'...
    Jun 04 08:47:36 ibis network[742]: The interface of network profile 'enp2s0' is already up
    However, the interface isn't really up, as it doesn't have an IP address:
    [root@ibis etc]# ip addr
    1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
    valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
    valid_lft forever preferred_lft forever
    2: eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 74:d4:35:18:11:36 brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.5/24 brd 192.168.1.255 scope global eno1
    valid_lft forever preferred_lft forever
    inet6 fe80::76d4:35ff:fe18:1136/64 scope link
    valid_lft forever preferred_lft forever
    3: enp2s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 74:d4:35:18:11:34 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::76d4:35ff:fe18:1134/64 scope link
    valid_lft forever preferred_lft forever
    4: wlp3s0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN group default qlen 1000
    link/ether 0c:8b:fd:75:13:d6 brd ff:ff:ff:ff:ff:ff
    and is listed as not active:
    [root@ibis etc]# netctl list
    enp2s0
    * eno1
    I must be doing something wrong, but what?
    Last edited by pgoetz (2014-06-04 22:01:36)

    according to ip addr, it looks like it actually does have an IP
    [root@ibis etc]# ip addr
    1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
    valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
    valid_lft forever preferred_lft forever
    2: eno1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 74:d4:35:18:11:36 brd ff:ff:ff:ff:ff:ff
    [b] inet 192.168.1.5/24 brd 192.168.1.255 scope global eno1[/b]
    valid_lft forever preferred_lft forever
    inet6 fe80::76d4:35ff:fe18:1136/64 scope link
    valid_lft forever preferred_lft forever
    3: enp2s0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 74:d4:35:18:11:34 brd ff:ff:ff:ff:ff:ff
    inet6 fe80::76d4:35ff:fe18:1134/64 scope link
    valid_lft forever preferred_lft forever
    4: wlp3s0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN group default qlen 1000
    link/ether 0c:8b:fd:75:13:d6 brd ff:ff:ff:ff:ff:ff
    have you tried "netctl stop eno1" && :netctl start eno1"?

  • Static nat & public IP on inside interface.

    Hello Guys,
    I am facing some issue related to static nat please provide your replies. let me explain the scenario.
    At site we have 4 cameras connected on switch and NVR (network video recorder) also connected on the same switch.
    Locally at site we are able to access the four cameras via http/web and also through NVR software .
    In order to access this cameras from remote location, we did static natting in router with pubic ip address for this cameras private IP address. Find nat table below.
    At remote site/from internet when we are adding the cameras in NVR software using public IP address. Later automatically public IP address resolving into private IP address.
    We are able to access cameras individually using http://<public ip address for camera> but when we try to add it in INVR software its changing public ip address to private.
    Camera Name
    Private IP address
    Public IP address
    Camera 1
    192.168.1.3
    xx. x8.23.115
    Camera 2
    192.168.1.4
    xx.x8.23.116
    Camera 3
    192.168.1.5
    xx.x8.23.117
    Camera 4
    192.168.1.6
    xx.x8.23.118
    Below is the configuration for the router. I am concerned about the public IP address which is assigned on internal/LAN interface instead of outisde interface by ISP. In other project i experienced Public IP address is at outside interface and private is at inside interface and we do static nat for inside to outside interface.
    But here when i access the cameras through public IP individually its working but not when i am adding this public IP in NVR software. May be something is wrong with static.
    interface GigabitEthernet0/0.1
     encapsulation dot1Q 868
     ip address 172.20.38.26 255.255.255.252
     ip nat outside
     ip virtual-reassembly in
    interface GigabitEthernet0/1
     ip address 192.168.1.1 255.255.255.0 secondary
     ip address 212.x.x.113 255.255.255.240                       (its a public IP address)
     ip nat inside
     ip virtual-reassembly in
     duplex auto
     speed auto
    ip nat inside source list 10 pool SLT overload
    ip nat inside source static 192.168.1.3 x.x.23.115
    ip nat inside source static 192.168.1.4 x.x.23.116
    ip nat inside source static 192.168.1.5 x.x.23.117
    ip nat inside source static 192.168.1.6 x.x.23.118
    ip route 0.0.0.0 0.0.0.0 172.20.38.25
    access-list 10 permit 192.168.1.0 0.0.0.255
    ip nat translation tcp-timeout 1000
    ip nat translation udp-timeout 1000
    ip nat pool SLT xx.xx.23.114 xx.xx.23.114 netmask 255.255.255.240
    ip nat inside source list 10 pool SLT overload
    Please advise on the above configuration. Your help in the above regard will be highly appreciated.
    Many Thanks in Advance.

    It is a bit odd to see the IPv4 address assigned this way. (Putting it on a Loopback would be a more elegant approach if the ISP is using private addresses for the WAN link.) But, there's nothing in here that would cause the NAT to fail. I suspect that the cameras are doing an HTTP redirect to their private IPv4 addresses at some point and this is causing your software to switch.
    With this configuration, there's no reason why you can't just put the cameras directly on the public addresses and forego the NAT entirely. If there is a redirect going on, they will redirect to the correct IPv4 address and things will still work.

  • Right way of defining constants - Interfaces or Classes?

    Two widely used ways to define constants in java projects are:
    1. Interfaces - Define constants in interfaces, they automatically become static, final and then implement the interface in concrete classes that need those constants.
    2. Classes - Use normal classes and define explicitly as static, final. Use CLASS_NAME.CONSTANT_NAME to access the constant in concrete classes.
    I have gone through the web on Best-practices for defining constants and its strongly recommended for not using Interfaces for defining constants.
    "The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface. " from     Effective Java, Joshua Bloch
    What is your take on this?
    Rgds

    I have gone through the web on Best-practices for defining constants and its strongly recommended for not using Interfaces for defining constants.
    "The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface. " from     Effective Java, Joshua Bloch
    I don't like grouping constants into an interface. I prefer keeping them closer to the classes that use them.
    %

  • Problem in Interface

    Hi,
    I doubt in Interface.
    Interface means : Only Method declaration & static final variable, there is no implementation of the methods. When we use it in the class, then we have to implement that method in our class, insted of that we can directly write that method.
    Regards
    DRA

    Interfaces are also commonly used to holdconstants.
    This is a bad idea.Here's one explanation why:
    Effective Java - Joshua Bloch, Chapter 4, Item #17: Use interfaces only to define types.
    The constant interface pattern is a poor use of interfaces. That a class uses some constants internally is an implementation detail. Implementing a constant interface causes this implementation detail to leak into the class's exported API. It is of no consequence to the users of a class that the class implements a constant interface. In fact, it may even confuse them. Worse, it represents a commitment: if in a future release the class is modified so that it no longer needs to use the constants, it still must implement the interface to ensure binary compatibility. If a nonfinal class implements a constant interface, all of its subclasses will have their namespaces polluted by the constants in the interface.

Maybe you are looking for