Shell we make a class as an interface?

shell we make a class as an interface then how ? give me one example

shell we make a class as an interface then how ?What do you mean? Currently something is a class and you want to change that type to an interface?
If so, then as for "shall you," I don't know. That depends on your needs, time, and skill level.
give
me one exampleAssuming you mean what I think you mean, it might be something like this:
// BEFORE
public class Foo {
    public void doStuff() { /* do some stuff */ }
Foo foo =new Foo();
foo.doStuff();
// AFTER
public interface Foo {
    void doStuff();
public class SimpleFoo implements Foo {
    public void doStuff() { /* do some stuff */ }
Foo foo = new SimpleFoo();
foo.doStuff();

Similar Messages

  • When to use abstract classes instead of interfaces with extension methods in C#?

    "Abstract class" and "interface" are similar concepts, with interface being the more abstract of the two. One differentiating factor is that abstract classes provide method implementations for derived classes when needed. In C#, however,
    this differentiating factor has been reduced by the recent introduction of extension methods, which enable implementations to be provided for interface methods. Another differentiating factor is that a class can inherit only one abstract class (i.e., there
    is no multiple inheritance), but it can implement multiple interfaces. This makes interfaces less restrictive and more flexible. So, in C#, when should we use abstract classes
    instead of interfaces with extension methods?
    A notable example of the interface + extension method model is LINQ, where query functionality is provided for any type that implements IEnumerable via
    a multitude of extension methods.

    Hi
    Well I believe Interfaces have more uses in software design. You could decouple your component implementing against interfaces so that
    you have more flexibility on changing your code with less risk. Like Inversion of Control patterns where you can use interfaces and then when you decide you can change the concrete implementation that you want to use. Or other uses for interfaces is you could
    use Interceptors using interfaces (Unity
    Interceptor) to do different things where not all of these is feasible or at least as straightforward using abstract classes.
    Regards
    Aram

  • Inner classes in my interface - ok, no k, indifferent?

    I have an interface and a set of ComparatorS which are only used for objects which implement the interface. So I put the ComparatorS in the interface like so (not actual code because it is for my job):
    public interface Abc {
      //Class loader should only do this once so they are basically singleton constants
      public static final Comparator C_1 = new C1();
      public static final Comparator C_2 = new C2();
      //... there is one more
      public String getSomething();
      public String getSomethingElse();
      //First Comparator inner class
      public class C1 implements Comparator {
         private C1(){ }
         //implements appropriate methods checking for instanceof Abc in the compareTo method
        //Compares something (using getSomething())
      /* Second Comparator inner class */
      public class C2 implements Comparator {
        //same thing
        //Compares somethingElse (using getSomethingElse())
    } //End interfaceUsage:
    Set s = new TreeSet(Abc.C_1);
    s.add(abc1);Because the Comparator implementations were specific to objects which implement the interface I felt that was the best way to make that fact clear. If they were over in a separate package it would be confusing that these are for the one interface. If they were in the same package as Abc it wouldn't fit (IMO) because they are more utility type classes.
    So it was either that or make them a singleton in their own class files or something like this and I found myself liking this.
    Any comments on pros/cons of doing it this way?

    I'm confused as to why it would make sense to put the
    Comparators 'in' the interface but not in the package
    with the interface. You can't put them 'in' the
    interface without putting them in the package. In
    reality, nesting them in the interface just creates
    classes in the interface's package.My whole deal is that after talking it out I see that it is bad for reuse to have something which could be so generic residing in a particular interface (and therefore deduced soon after that in the same package as my interface). Which made me decide not to have the inner classes because it IS in the same package at that point. But I am saying that is bad. As I tried to state before, for the same reason I now think it is bad to have the classes in the interface (not much i.e. no reuse outside of the interface) then it is bad to have it in the same package as the interface (unelegant reuse outside of the package). Because if the getSomething() is getName() that could be used as a comparator for many different objects in different packages. I don't want to limit. This stance was a progression, once I decided not in the interface, I then also decided not in the same package.
    Java is strongly typed. If the class isn't an
    instance of the class you are casting to (in this
    case the interface) it doesn't matter if it has a
    method with the same signature. The cast will fail.Yes, of course, but like generics, you are not limited to just one type (Object is the type of the parameter). So I can either use instanceof before casting (not the best way) or I could have private overloads of the compareTo() method, a new one for every type I support and each supported type which has a getName() could come from a couple different packages. Not that generics does it the same way but on top of being about to declare hierachies that a genericized object can deal with you can also have comma delimitted other objects. They don't have to be related by package or hierarchy in generics. So I don't think it would be so bad for my Comparator to be (if it fit that these different types all had the same method needed by my Comparator).
    >>
    Here's anothe reason not to do that. Let's say that
    someone is using the interface. They need to compare
    it to something else, if the Comparators are right
    there with the interface, they will be likely to find
    them. If they are in some other package, they'd have
    to know where to go look for them.If that is the case, where I was worried about easy to find then I would go back to using inner classes with each Comparator as a constant. If I was worried about ease of finding where these ComparatorS are over code reuse across packages.
    I mean, I think if I am going to tie the ComparatorS so close to a particular Type then I am going to add it as an inner class whether my type was an interface or a class. At least that is what I am thinking now.
    >
    This is what I am talking about. So many Java
    developers treat packages like filing cabinets. I
    put things that do this here and things that do that
    there. But this is actually not very useful and it
    hamstrings your designs.
    Java doesn't have a friend class syntax like C++. So
    there's no way to say this class over here has access
    to this but no one else does. These kinds of
    relationships are very desireable. Some classes will
    need to access things in another class that shouldn't
    be public. You can do this cleanly if they ae in the
    same package but not otherwise.But I am not talking about taking an abstract class putting it in pack1 an a subclass in pack2. I am talking about putting a utility class that could eventially work on 50 classes in a place that is playingfield neutral and not in the original type it deals with today only. I am dealing with public accessor methods on my objects.
    >
    For example. Let's say you want to create a Factory
    (I'm using Factory in a loose way here not
    necessarily a GoF Pattern) for a public class. You
    don't want every class to have access to contructor
    because it creates the Object without initializing
    all the necessary atttributes. The factory is
    specially crafted to do this with protected info and
    access rights. If you put the class and the factory
    together it;s a snap. You create a package-protected
    constructor, some package-protected methods and/or
    fields and do it. No class outside the package will
    be able to do these dangerous operations. How do you
    do this if you have a factory package and a data
    object package?That is a whole nother situation I think. In that case it is obvious. I thought my situation was a little less obvious because of the utility nature of the classes (ComparatorS) that I was dealing with.

  • Make Your Classes Uncloneable

    Hello,
    what�s about the rule �Make Your Classes Uncloneable� you can read every here and there? See for example [http://www.roseindia.net/linux/tutorial/linux-howto/Secure-Programs-HOWTO/java.html|http://www.roseindia.net/linux/tutorial/linux-howto/Secure-Programs-HOWTO/java.html] or [http://www.securingjava.com/chapter-seven/chapter-seven-1.html|http://www.securingjava.com/chapter-seven/chapter-seven-1.html] (rule 8). Of course, if I implement Cloneable I have to take care that the clone method does the security checks I�m normally doing in the constructor. But if I don�t implement Cloneable, why should I explicitly make my class uncloneable by throwing that exception in the clone method?
    And how is the subclass stuff working (rule 8 again)? I have a class A which does not implement Cloneable and has a security check in the constructor. Now an attacker creates a subclass of class A which does implement Cloneable. Lets say I have successfully generated an object of class A, how can that be cloned by an attacker using his subclass?
    Thanks!

    But if I don�t implement Cloneable, why should I explicitly make my class uncloneable by throwing that exception in the clone method? And where in the JavaDoc for Cloneable does it say that you have to do that?
    Here's the complete doc from http://java.sun.com/j2se/1.5.0/docs/api/index.html
    >
    A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.
    Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.
    By convention, classes that implement this interface should override Object.clone (which is protected) with a public method. See Object.clone() for details on overriding this method.
    Note that this interface does not contain the clone method. Therefore, it is not possible to clone an object merely by virtue of the fact that it implements this interface. Even if the clone method is invoked reflectively, there is no guarantee that it will succeed.
    >
    Seems pretty explicit to me: it's a marker interface used only by Object's implementation of clone(). Why do people get so bent about it?

  • When to make a class a bean?

    I can understand that if you have a GUI type class where you might want to make the class a Bean so that it can be used in tools like BeanBox.
    But what if it is a non visible class? For example say a class that is used to interface to piece of equipment over the serial port? Are there any advantages to making the class a Bean?

    Ok. My info may be a little out of date, but I'll try.
    In object oriented programming, we have these things called patterns. They are called that because that's what they are caled in the original book by the "gang of four", whose names I can't recall. An example of a pattern is the idea of passing an event around, or having graphical objects "inside" other ones, or making a class that serves as an interface to a complex set of other classes. These patterns are not always directly supported by the APIs or language, they are more abstract than that - ways that we programmers go about architecting solutions to certain kinds of problems. (nb: a pattern is not the same thing as an algorithim). Of course, some patterns are supported directly by the APIs: EventObject, EventListener etc.
    One common pattern is an object that holds a set of values, that fires events and so on. Of course any object can do this, but architecturally speaking, some objects work that way more naturally than others. In Java, we call such an object a JavaBean.
    Java supplies a standard for JavaBeans at http://java.sun.com/products/javabeans/docs/spec.html . This standard specifies that a java bean has a null argument constructor, it has getters and setters and that if a bean has a getFoo() method and a setFoo() method, then these together mean that the bean has a "property" named Foo, and so on.
    Now physically, the only thing that a java bean must have is:
    it must be public,
    it must have a public, no-argument constructor
    However, architecturally, we make a load of assumptions. For instance, if your class has a getFoo() and setFoo() method, but they have absolutely nothing to do with each other, then you class isn't a JavaBean, even though physically the compiler and tools have no way to know this. Likewise, if your class has a public no-arg constructor, but your class requires that you call the setup() method for it to work properly, then it is not a JavaBean. JavaBeans can be initialised into a reasonable starting state with the constructor alone.
    So JavaBean or not JavaBean is not a class you inherit or an API you use, it's a way of doing things.
    Having said that, there is api support for JavaBeans in the java.bean package. You can create "BeanInfo" classes for your beans that contain metadata about the beans: long textual descriptions for the properties, icons for tools to use when displaying the beans and so on.
    As for JSPs:
    From memory, you can tell your JSP that an instance of a bean is to be created for each session that the JSP deals with. So say we make a bean that acts as a shopping cart, with items that themselves are beans (item number, quantity). Inside the JSP you can do things like "print shopping cart.item[2].name", and the JSP will know to convert this to a call to foobean.getItem(2).getName(). The reason for making it a bean is to make it possible for the web server to manage the creation of these things and the retreiving of them on a session-by-session basis. They can also be passed as arguments and so on. Another nice reason to use a bean is that you can encode derived values as getter methods on the bean (eg: getTotalPrice()). This is a nice place to put such logic.
    The JSP spec is at http://www.jcp.org/aboutJava/communityprocess/final/jsr053/ . (dont confuse it with the servlet Spec, which is on the same page). See section 4.1: Standard Actions/usebean.

  • What is the diff b/w Abstract class and an interface ?

    Hey
    I am always confused as with this issue : diff b/w Abstract class and an interface ?
    Which is more powerful in what situation.
    Regards
    Vinay

    Hi, Don't worry I am teach you
    Abstract class and Interface
    An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
    Edited by SASIKUMARA
    SIT INNOVATIONS- Chennai
    Message was edited by:
    sasikumara
    Message was edited by:
    sasikumara

  • I want to make gImage Class extends Image and use Graphics2D

    Sorry, my english short...
    I want to make gImage Class extends Image and use Graphics2D
    I trying to do...
    make class gImage..
    extends Image class. (Inheritance)
    but Image class is abstract class..
    And I want to use gImage class same as Image class.
    I can't use constructor... because by Abstract calss...
    How do i?
    Help me.. plz...
    And I want to use Graphics2D at Applet Game, But not use Java JDK Plug-in...
    No Way?

    You need to use BufferedImage with 2D or RenderedImage with JAI.
    BufferedImage effectivley extends an Image so you can
    draw it to screen in paintCOmponent.
    I use an Extended JPanel to draw an image in a Panel with this.
    MArk

  • How to make a class immutable?

    I hav attend the interview where they ask this question.
    I know little bit is Make the class final and declare all variables as static final .
    Can any Help me.
    This question

    Thi is just my opinion;
    An immutable object is an object that once created, it's values can no longer be changed.
    Thus an immutable object could be an object that allows it's values to be changed only when created with the use of the constructor, and only has get methods to retrieve those values (no set methods).
    @Peetzore
    Defining them as final is something I never did, however it makes sense :) and will start doing so as well
    Regards,
    Sim085

  • How to make standard class as mandatory in eupiment master[class overview]

    Hi,
    In equipment master if I want to make standard class as mandatory field [Check standard class].
    If any any configuration is available please give me the path.
    Else Any user exist is available please suggest me.
    Reward points are available
    Thanks in advance.
    Hanamanta

    hi,
    Just follow the menu path given.
    Cross-Application Components > Classification System >
    Classes > Maintain Object Types and Class Types
    Assign required class type to table EQUI and remove the class types which are not required.
    This will definitely solve ur problem.
    with regards,

  • To read value of name1 to eh_onsave and also to make uitility class.

    Hi,
    My requirement is to read (get) the value of name1(bp_head, bphead/account details,header,name1) to eh_onsave.
    Please suggest me to achieve this through iv_relation_name.
    I have written select statement in eh_onsave,they suggested to make utility class and call the method of that utility class to get values.
    How to to achieve this .
    Regards,
    Kishore.

    Hi,
    EH_ONSAVE method is in BPHEADOverview which has a context node BuilHeader bound to component controller context node PARTNER. You can directly read name1 from BUILHEADER, not necessary to use iv_relation_name. Use the below sample code in eh_onsave method,
    data: lr_ent       type ref to cl_crm_bol_entity,
             lv_name1 type string.
        lr_ent ?= me->typed_context->builheader->collection_wrapper->get_current( ).
        lv_name = lr_ent ->get_property_as_string( iv_attr_name = 'NAME1'  ).
    Regards,
    Arun

  • How to make a class an array

    Hello, i am very confused as to how to make an array inside a class and use it from another class. For example, when making a "Book of hotties" where i would create entries in a book(objects) of hot women ,with parameters
    name, last name, phone number, and rating, and i am supposed to make a class for the book itself with a Person [ ] blackBook, and also a separete class called Person where i would create each person. How would i go about creating this array and where would i create it? and from that how can i access it in order to perform methods like sorting and checking entries? Tnx in advance.
    Edited by: Secmugen on May 5, 2009 6:19 AM
    Edited by: Secmugen on May 5, 2009 6:20 AM

    You probably need to start here: http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html
    There is also a Java collection called ArrayList which is suitable for storing and retreiving objects such as BlackBook, Person etc...
    To access elements of an array within a class you would most likely use a public getter method. eg.
    public class BlackBook {
       private ArrayList<Person> persons = new ArrayList<Person>();
      public ArrayList<Person> getPersons() {
         return this.persons;
      public Person getPerson(int index) {
        this.persons.get(index);
    };etc..

  • Class implementation for interface

    Hello,
    I am a beginner in ABAP Objects.
    In the coding of method if_swf_ifs_workitem_exit~event_raised of class CL_SWF_UTL_EXIT_NEW
    There is the instruction follow :
    *Get the workflow container
    irh_container ?= im_workitem_context-> get_wf_container()
    Im_workitem_context is interface type  "IF_WAPI_WORKITEM_CONTEXT"
    If I execute in debug mode I see the implemtation class of this interface (im_workitem_context)  is "CL_SWF_RUN_WORKITEM_CONTEXT"
    But where this information of implementation is defined ? (I saw nothing)
    Regards
    Christine
    Edited by: chris_75 on Sep 7, 2010 4:22 PM

    Interfaces allow to implement highly scalable object oriented applications.
    Interface is a kind of a template for a real class which forces this class to implement methods defined in an interface.
    The main characteristics of an interfaces are:
    - they DO NOT contain any implementations (so there is nothing like INTERFACE ... IMPLEMENTATION - they have only DEFINITIONS - implementations are within classes)
    - they have only PUBLIC sections.
    Why we need an interface. The answer is simple:
    We want to handle some objects uniformly from one application compotent, whereas these objects may behave differently inside.
    Example:
    Let's say we need to build a sorting program for numbers.
    The program would have an interface variable L_RIF_SORTER of an interface LIF_SORTER. LIF_SORTER has a method definition SORT with an C_TAB changing parameter.
    Sorting application would call the sorting algorithm as follows:
    L_RIF_SORTER->SORT( CHANGING c_tab = l_tab ).
    Now is the main point:
    We want to have 2 kinds of sorting algorithms implemented, let's say BUBBLE SORT and QUICK SORT.
    To do so, we implement 2 classes: LCL_BUBBLE_SORT and LCL_QUICK_SORT.
    Both classes implement interface using the statment INTERFACES in a public section.
    The user would have to choose the algorithm from an input field. Depending on the content of this field the sorting application would instantiate one class or the other using the statement:
    CREATE OBJECT l_rif_sorter TYPE (variable_with_class_name).
    THis is the point where ABAP gets to know the real object and its type behind the interface.
    This approach is generally called the STRATEGY PATTERN. See Wikipedia for this.
    I hope I answered your question.
    Regards,

  • When to use abstract class compared to interface

    hi
    can some one plase advise me when to use abstract class compared to interface?
    Example will be appreciated...

    So an abstract class can carry implementation. This can be used to formulate a rule of thumb as to when to use it over an interface.
    If you have a so called type specialization relationship between the subtypes and the supertype then they're likely to benefit from shared implementation provided by the supertype, so use class (abstract or concrete) extension in this case. Type specialization is when the supertype represents a general concept like Fruit and the subtypes are specialized forms of that like Apple and Banana.
    Another common kind of relationship is called type expansion. In this case the subtypes are unlikely to have any use of implementation provided by the supertype, so use interface implementation. Type expansion is when the supertype represents a specific character the subtypes take on. For example Apple and Bicycle ure unrelated in the type specialization sense but still can share a common character like Comparable. The subtypes have been expanded to include the supertype character, namely the ability to be compared.

  • To find the implementing classes of an interface

    Hi,
    Does anyone know a function module or class using which I can find all implementing classes of an interface?
    Regards,
    Sukru

    Hello Sukru
    If you are working already on SAP releases >= 6.20 then you will see all implementing classes if you display the interface in SE80 (tree display -> subnode of the interface).
    Alternatively, you can call method <b>GET_IMPLEMENTING_CLASSES</b> of class <b>CL_OO_INTERFACE</b> (available on >= 6.40, perhaps on 6.20, too).
    Regards
      Uwe

  • Can I make a class holding multiple GUI components and make it visible?

    I am implementing an MDI where the different JInternalFrames are filled with a JPanel with components. Since the contents of my screen is dynamically generated, each screen can have multiple Jlabels, JTextFields, etc.
    So I thought, I make a class containing the representation of one row of GUI components on my screen, which is: one JLAbel and 4 JTextFields.
    Here is the code which adds the components to the panel:
    // create panel
    JPanel qpanel = new JPanel();
    qpanel.setLayout(new BoxLayout(qpanel, BoxLayout.Y_AXIS));
    qpanel.add(Box.createVerticalStrut(5));
    //add rows to panel
    for( int i = 0; i < nrRows; i++)
    // qpanel.add(new JLabel("Hello how are you"));
    qpanel.add(new ProcessRow("hello","how","are","you"));
    // add panel to scrollpanel
    this.getViewport().add(qpanel);
    Here is the ProcessRow class:
    public class ProcessRow extends JComponent
    public JLabel rowLabel = null;
    public JTextField myCost = null;
    public JTextField saratogaCost = null;
    public JTextField sapCost = null;
    public JTextField totalCost = null;
    public ProcessRow() {
    super();
    public ProcessRow(String LABEL,
    String DEFAULTCOST,
    String SARATOGACOST,
    String SAPCOST){
    super();
    JLabel rowLabel = new JLabel(LABEL);
    JTextField myCost = new JTextField(DEFAULTCOST, 6);
    JTextField saratogaCost = new JTextField(SARATOGACOST, 6);
    JTextField sapCost = new JTextField(SAPCOST, 6);
    JTextField totalCost = new JTextField(6);
    If I add the label "Hello how are you" directly to the panel, it shows fine but if I use my ProcessRow class, nothing shows.
    How can I make it visible and if not,
    how can I dynamically keep adding all these GUI components without loosing control over the components.
    Thanks,
    Johnny

    Modify your ProcessRow:
    (1) First extends JPanel ( Container, not Component)
    (2) Add Label and TextField to the container
    public class ProcessRow extends JPanel
    public JLabel rowLabel = null;
    public JTextField myCost = null;
    public JTextField saratogaCost = null;
    public JTextField sapCost = null;
    public JTextField totalCost = null;
    public ProcessRow() {
    super();
    public ProcessRow(String LABEL,
    String DEFAULTCOST,
    String SARATOGACOST,
    String SAPCOST){
    super();
    JLabel rowLabel = new JLabel(LABEL);
    JTextField myCost = new JTextField(DEFAULTCOST, 6);
    JTextField saratogaCost = new JTextField(SARATOGACOST, 6);
    JTextField sapCost = new JTextField(SAPCOST, 6);
    JTextField totalCost = new JTextField(6);
    // add everything to the container.
    add(rowLabel);
    add(myCost);
    add(sapCost);
    add(totalCost);
    }

Maybe you are looking for

  • Creating snapshot in SSRS 2008 R2 report will disable some parameters.

    Hi guys. I'm new to SSRS, so the question that I'm going to ask might sound stupid, hope you guys don't mind. I have a few reports that display data based on the snapshot. I found out that some of the parameters on certain reports were disabled and s

  • In Credit Memo Net Value is coming 0.

    Dear SD Expert, I have created Credit Memo with Reference Credit memo request. While creating Credit memo (VF01) the Net Value is 0. But the Billed quantity is coming correct in the system. In Credit Memo request(VA01) every thing is ok, Quantity and

  • How to change SessionTimeOut value after deployed war file in SunAPP Server

    Hi Guys, Any one can help and give some guidence How i can change the session time out value in web.xml after deployed the file on sun one application server.This is the code given below which i have to change the time of session from 5 minutes to 1

  • Buddy in app buddy list but not in menubar buddy list

    For some reason, one of my Buddies does not show up in the Buddy List available from the menubar. That buddy (and all buddies) are listed in the Buddy List shown within the iChat application. I tried deleting the preferences plist files as referenced

  • I thought I was archiving my mail, but.....

    Folks, In preparation to buy a new MAC, Mr. Smartypants copied his mailboxes (Home>Library>Mail>Mailboxes) into a separate folder, then deleted them from my various active mailboxes in MacMail, which I kept. I have subsequently gotten the new MAC, an