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.

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

  • When should I use abstract classes and when should I use interfaces?

    Can any body tell me in which scenario we use /we go for Interface and which scenario we go for abstract class, because as per my knowledge what ever thing we can do by using Interface that thing can also done through abstract class i mean to say that the
    behavior of the two class.
    And other thing i also want to know that which concept comes first into the programming abstract class or Interface.
    S.K Nayak

    The main differences between an abstract class and an interface:
    Abstract
    An abstract class can contain actual working code (default functionality), and can have either virtual or abstract method.
    An abstract class must be sub-classed and only the sub-classes can be instantiated. Abstract methods must be implemented in the sub-class. Virtual methods may be overridden in the sub-class (although virtual methods typically contain code, you still may
    need/want to override them). A good use for an abstract class is if you want to implement the majority of the functionality that a class will need, but individual sub-classes may need slightly different additional functioality.
    Interface
    An interface only contains the method signatures (method name and parameters), there is no code and it is not a class.
    An interface must be implemented by a class. An interface is not a class and so it cannot be sub-classed. It can only be implemented by a class. When a class implements an interface, it must have code in it for each method in the interface's definition.
    I have a blog post about interfaces:
    http://geek-goddess-bonnie.blogspot.com/2010/06/program-to-interface.html
    (sorry, I have no blog posts specific to abstract classes)
    ~~Bonnie DeWitt [C# MVP]
    http://geek-goddess-bonnie.blogspot.com

  • Most commenly used abstract class in java.

    hi all,
    can anyone please tell me, what is most commonly used abstract class in java. this question was asked in interview.

    I hate interviewers when they ask about specifics of some classes.The fact that you hate it doesn't automatically follow that it's a bad question from the perspective of the person conducting the interviewer. You don't know what the real question is.
    Bad "real" question: Do you know the statistics of Java usage off the top of your head?
    Good "real" question: Do you know that Object isn't Abstract and can you name a few Abstract classes off the cuff?
    Even then Programmers are so literal minded - the real question may be "Talk about what you know a bit."

  • Design question about when to use inner classes for models

    This is a general design question about when to use inner classes or separate classes when dealing with table models and such. Typically I'd want to have everything related to a table within one classes, but looking at some tutorials that teach how to add a button to a table I'm finding that you have to implement quite a sophisticated tablemodel which, if nothing else, is somewhat unweildy to put as an inner class.
    The tutorial I'm following in particular is this one:
    http://www.devx.com/getHelpOn/10MinuteSolution/20425
    I was just wondering if somebody can give me their personal opinion as to when they would place that abstracttablemodel into a separate class and when they would just have it as an inner class. I guess re-usability is one consideration, but just wanted to get some good design suggestions.

    It's funny that you mention that because I was comparing how the example I linked to above creates a usable button in the table and how you implemented it in another thread where you used a ButtonColumn object. I was trying to compare both implementations, but being a newbie at this, they seemed entirely different from each other. The way I understand it with the example above is that it creates a TableRenderer which should be able to render any component object, then it sets the defaultRenderer to the default and JButton.Class' renderer to that custom renderer. I don't totally understand your design in the thread
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=680674
    quite yet, but it's implemented in quite a bit different way. Like I was saying the buttonClass that you created seem to be creating an object of which function I don't quite see. It looks more like a method, but I'm still trying to see how you did it, since it obviously worked.
    Man adding a button to a table is much more difficult than I imagined.
    Message was edited by:
    deadseasquirrels

  • 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

  • Why use abstract classes?

    Why should I use abstract classes instead of a regular class with empty method bodies? Just better design? Is there some logical or performance based reason?

    Why should I use abstract classes instead of aregular
    class with empty method bodies? Just better design?Is
    there some logical or performance based reason?Because it describes what you're doing.
    If you define a "regular" class with empty message
    bodies, everyone who looks at it will say "WTF is he
    trying to do" or, if they're charitable, "Look,
    Harvey, someone who's trying to make Java look just
    like C++!".
    sigh Maybe answers like THIS are why people keep asking the same question.
    Here's a couple things an abstract class does that a "regular" class with empty methods bodies doesn't:
    1) An abstract class cannot be instantiated.
    2) An abstract class forces it's abstract methods to be implemented.
    If you were to extend a non-abstract class with empty method bodies, you wouldn't have to override the methods... you could just leave them empty. An abstract class forces it.
    There's a lot more reasons... those are a couple obvious ones.

  • Hi when i use treeMap class and if i exit the program

    hi
    hi when i use treeMap class and if i exit the program,
    what will happen? the information that i put in the treeMap will be disappear??
    if it is like that,,how am i able to retrieve my data...when i restart my program..
    once i put ID as key and put my customer information,
    in it, after exit my program,, and i can't find
    my customers by their ID,,,,,,,,,how can,,i solve it......

    what will happen? the information that i put in the
    treeMap will be disappear??Yes. Of course. If you want data to hang around you have to tell the computer. If you want anything to happen you have to tell the computer.
    if it is like that,,how am i able to retrieve my
    data...when i restart my program..Tada! Tell the computer. Your simplest option is to use Serialization.
    Before exiting your program, serialize your TreeMap to disk. After starting your program serialize your TreeMap from disk.
    First stop should be your text book to learn what Serialization is and how it works, then try to write some code, then ask us to help with any problems.
    Dave.

  • Why are we using Abstract class?

    Why are we using Abstract class? What is specify use of Abstract class?

    The way I understand it....and I may be wrong because
    I am very new....is that by making the class abstract
    you will add abstract methods to it. Those abstract
    methods MUST be defined in in any subclass that
    inherits from the abstract class thereby making the
    abstract a template for subclasses.
    If your animal class is abstract then you would need
    an abstract method (Which is just siganture, no body)
    of say "numberOfLegs". Then in your dog and cat
    classes which extend animal you must define a
    "numberOfLegs" method with appropriate code.it isn't mandatory for an abstract class to have abstract methods. if a class does have abstract methods, the class must be abstract. but the following is perfectly legal
    public abstract class NoAbstractMethods {
      public void doStuff() {
         // do stuff
    }a subclass of an abstract class can also be abstract, and as such need not implement any additional methods

  • EJB question: How to use abstract class in writing a session bean?

    I had written an abstract class which implements the session bean as follow:
    public abstract class LoggingSessionBean implements SessionBean {
    protected SessionContext ctx;
    protected abstract Object editRecord(Object obj) throws Exception;
    public LoggingSessionBean()
    super();
    private final String getBeforeUpdateImage(Object obj) throws Exception {
    // implement the details of extracting the backup image ...
    public void setSessionContext(SessionContext ctx)
    this.ctx = ctx;
    private final void writeThisImageToDatabase(String aStr) {
    // connect to database to write the record ...
    public final Object update(final Object obj) {
    try {
    final String aStr = getBeforeUpdateImage(obj);
    writeThisImageToDatabase(aStr);
    editRecord(obj);
    } catch (Exception e) {
    ctx.setRollbackOnly();
    This abstract class is to write the backup image to the database so that other session beans extending it only need to implement the details in editRecord(Object Obj) and they do not need to take care of the operation of making the backup image.
    However, some several questions for me are:
    1. If I write a class ScheduleSessionBean extending the above abstract class and the according 2 interfaces ScheduleSession and ScheduleSessionHome for this session bean (void update(Object obj); defined in ScheduleSession), do I still need to write the interfaces for LoggingSession and LoggingSessionHome?
    2. If I wrote the interface LoggingSession extending EJBObject where it defined the abstract methods "void update(Object obj);" and "void setSessionContext(SessionContext ctx);", that this meant I needed to write the ScheduleSession to implement the Logging Session?
    3. I used OC4J 9.0.4. How can I define the ejb-jar.xml in this case?

    Hi Maggie,
    1. do I still need to write
    the interfaces for LoggingSession and
    LoggingSessionHome?"LoggingSessionBean" can't be a session bean, because it's an abstract class. Therefore there's no point in thinking about the 'home' and 'remote' interfaces.
    2. this
    meant I needed to write the ScheduleSession to
    implement the Logging Session?Again, not really a question worth considering, since "LoggingSessionBean" can't be an EJB.
    3. I used OC4J 9.0.4. How can I define the
    ejb-jar.xml in this case?Same as you define it for any version of OC4J and for any EJB container, for that matter, since the "ejb-jar.xml" file is defined by the EJB specification.
    Let me suggest that you create a "Logging" class as a regular java class, and give your "ScheduleSessionBean" a member that is an instance of the "Logging" class.
    Alternatively, the "ScheduleSessionBean" can extend the "Logging" class and implement the "SessionBean" interface.
    Good Luck,
    Avi.

  • OC4J 9.0.4 migrate to 10.1.3.1 JSP fails using abstract class for ResultSet

    Consider the following JSP code snipet:
    <%
    com.class.SQLDataSource detail = ((com.class.SQLDataSource)request.getAttribute("AcctList"));
    %>
    <%while detail.next()) {detail.getRow();%>
    <tr ...>
    <td ...><%= detail.getString("ACCT") %></td>
    </tr>
    <%}%>
    blah, blah, blah
    class snipet looks like this:
    public abstarct class SQLDataSource extends serializable {
    private ResultSet resultSet = null;
    private PreparesStatement stmt = null;
    public boolean next() throws SQLException {
    boolean result = getResultSet().next();
    return (result);
    public String getString(String columnName) throws SQLExcpetion {
    return getResultSet().getString(columnName);
    public void execute() throws SQLException {
    -- checks stmt
    -- if null generates resultSet from "AcctList.sql" query
    -- if not null, re-executes as-is stmt for a query only
    protected ResultSet getResultSet() throws SQLException {
    execute(); // see above
    return resultSet;
    The problem:
    <%= detail.getString("ACCT") %> generates a NullPointerException
    Yet, if I add debug statements in the SQLDataSouce class, they conclusively show that resultSet has 1902 rows and I can diplay the contents on these rows (on the console, of course, the JSP still generates a NullPointerException).
    If I "hardcode" the creation of a ResultSet in the JSP, the pages displays properly (not the desired method).
    PLEASE TAKE NOTE: This JSP/Class combination works PERFECTLY in OC4J 9.0.4 using JDeveloper 9.0.5.2. When I deploy the **EXACT SAME** JSP/Class combination in JDeveloper/OC4J 10.1.3.1, I receive the NullPointerException.
    So what this feels like to me (and my VERY limited J2EE experinece) is that the abstract class SQLDataSource has somehow lost/closed/dropped/corrupted resultSet when "returning" to the JSP for display of the contents of resultSet. This is, of course, a laymans explanation of the experienced effect of running this code.
    It makes me wonder if under 10.1.3.1 "something more" must be done so that the (abstract) SQLDataSource class can operate in the same way it did under 9.0.4.
    Last note: this NullPointerException happens whether I deploy to standalone OC4J 10.1.3.1 or if I execute my application withing JDevloper's Embedded OC4J instance.
    Any Assistance on this MOST aggrivating problem would be greatly appreciated.
    Others have yet to solve it in similar posts of mine. Hopefully this more definitive description will help YOU be my personal HERO.
    Ed.

    repost to pique interest

  • Please give me the information when to use inner classes in applications

    HI,
    please give me when to use the innerclasses

    > HI,
    please give me when to use the innerclasses
    Use them when you want to create a class within another class.
    Now gimme all 'er Dukes!!!

  • When to use Nested Class/Inner Classes ?

    I am not very clear, when to use nested/inner classes..
    The scenario is :-
    class ABC
    //ABC need to store multiple instance of class XYZ
    class XYZ
    int member1;
    int member2;
    One approach is
    class ABC
    class XYZ
    //vector of class XYZ instances is stored in class-ABC
    or another approach is Class XYZ can be in separate JAVA file.
    Query:-
    1) Is there any difference between nested or Inner class...or are they same?
    2) When should they be used....Is it good to use in above scenario.
    3) What are the disadvtanges/advantages of using the Nested
    class.

    Query:-
    1) Is there any difference between nested or Inner
    class...or are they same?I really don't get it. Yes there is a difference between having an inner class, and a class in a separate file, but a nested class is an inner class.
    2) When should they be used....Is it good to use in
    above scenario.To write an inner class is a design decision. Do other classes need to know about the class XYZ or not? Do the XYZ class need to know about the inner working of the ABC class? How complex is the XYZ class etc.
    >
    3) What are the disadvtanges/advantages of using the
    Nested
    class.See above.
    /Kaj

  • Using Abstract Class Methods

    I just want to know that in how many ways can we use the non abstract methods of the class without extending the class(dont want to implement all abstract methods of the parent class).One way is that if the methods are static then we can use CLASSNAME.METHODNAME().Is their any other way of doing it

    none at all. not a single one. by definition, a non-static method has to be invoked on a particular instance of a class, and an abstract class cannot be instantiated. somebody is probably going to say you can do this:
    abstract class AbstractClass {
      abstract void minceAbout();
      void talkRubbish() {
         // do stuff
    new AbstractClass() {
        void minceAbout() {}
    }.talkRubbish();but that is extending the AbstractClass, no matter what their argument. why d'you ask, anyway? why not implement the methods? sounds like a design smell

  • @Override when extending an abstract class

    Hi!
    I have an abstract class A with one abstract method B. I then created a class C which extended A. Eclipse then automatically created the abstract method. But it also added @Override.
    Like this:
    @Override
    protected void B()
         // something
    }What does the @Override do?

    http://java.sun.com/docs/books/tutorial/java/javaOO/annotations.html

Maybe you are looking for

  • Address book and google syncing

    I would like to sync my google contacts with address book. I have gone into the preferences of address book and set it to "Synchronise with google" and entered my info. It will pull the email address', however that is all that it will pull. The names

  • Remove wine trash from context menu

    If I right-click on most files in linux, there is all kinds of wine options there that I do not want. Namely, notepad (2 instances), Internet Explorer, etc. How do I get rid of it without uninstalling wine? I am using XFCE with PCMANFM as desktop man

  • Safari running very slow, freezing and unexpectantly quiting

    Please help!!! this started about a week ago and is driving me mad! I have changed the proxies, turned off extensions and reset safari Here is the EtreCheck Hardware Information:           MacBook Air (11-inch, Late 2010)           MacBook Air - mode

  • Can mpls support multicast?

    Hi, Can mpls support multicast packets? Meaning, can multicast packets be sent to destinations over mpls network? If so, how does it work? I read in this forum somewhere that someone mentioned mpls and multicast can co-eixt. What exactly does it mean

  • Mozilla thunderbird will not open or sync profile on NAS device

    Was running two computers with thunderbird both sync to the same profile stored on a NAS device. NAS device lost a drive but profile remained in tact. Now TB will not load the profile but when asked where the profile is located TB shows correct locat