Difference between abstract classes and interfaces

I actually wonder about what are the differences between abstract classes and interfaces may somebody give an example code about it?
and i have one more question how can i use interfaces like multiple inheritance ? i mean when i implement an interface like
class a extends b implements c,di have to use all c and d methods but what that methods means?
I mean as i know we cannot make implementations of methods in interfaces
but for example in runnable interface there is a method like run() and it has been defined somewhere because it knows what to do(i mean when it will run), i just write my code into that method .

Once you get past the starting point (I am referring to the OP here), there are a few salient differences:
You can only extend (or generalize) a single superclass; however, you can implement (or realize) multiple interfaces. As such, all things being equal, using an interface in lieu of an abstract class 'frees' your design. Later, if you want the implementor of an interface to inherit from another class, there is not issue.
Any abstract method specifies a contract. However, abstract classes allow you to also add common behavior to subclasses. This is an overused justification for abstract classes, IMO. You can achieve the same effect using delegation and still having interfaces.
Always program to interfaces wherever possible. This means that you define an interface and have an implementing class (usually at a minimum). Do not do this for all your classes, but rather the ones that make your system unique (the domain model or M in MVC architecture). This allows you to later change implementation with a minimal amount of refactoring. This is a core precept from the Group of Four and any number of decent programming books.Best of luck.
- Saish

Similar Messages

  • What is the difference between Abstract class and Interface ?

    Hi,
    Could u plz tell me the difference between Abstract class and Interface?
    Thanks in advance.
    Gopi

    Lots.
    An abstract class can contain some method implementations, or indeed all the method implementations. It may contain methods with all the various access modifiers. It cannot be instantiated. A class may inherit from only a single abstract class.
    An interface contains only public method stubs and constants. A class may implement multiple interfaces. An interface cannot (obviously) be instantiated.
    Abstract classes are particularly useful when you need to provide a semi-complete implementation for reuse. Interfaces are used more like types.
    Look at java.util.* for some good examples of the use of both.

  • Difference between abstract class and interface

    Hi everyone,
    CAn anyone explain why the following happen????
    Abstract class can have a constructor, Interface cannot.
    Abstract class can have static methods, Interface cannot.

    What are the advantages of defining constant
    variables in Interfaces?Not many.
    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.
    In summary, interfaces should only be used to define types. They should not be used to export constants.

  • What's the difference between Abstract Class and Interface?

    Dear all,
    Can anyone give me some hints about this topic?
    Thanks.
    Leo

    an abstract class may have some methods already implemented in the abstract class but an interface has no methods implemented
    I think it's just that simple.
    For your design needs, you just choose what you need : )
    Cheers
    Stephen

  • Difference between Abstract Classes Vs Interface

    Hi,
    Can u pls mention all the differences between Abstract Classes and Interface.? I've mentioned the differences I've known here.
    Known Differences:
    (*) An interface cannot implement any methods, whereas an abstract class can.
    (*) A class can implement many interfaces but can have only one superclass
    Can U pls mention at what situation(practical situation) we've to go for abstract class or Interface?
    Tell me the situation when we have to go for abstract class?
    Tell me the situation when we have to go for interface?
    Please Reply me
    Thanks & Regards
    Venkatesh

    There are more differences, and one really important is that abstract classes can also define class variables, while interfaces cannot. I think the question of when to use interfaces or abstract classes is not always easy to answer, but yourself have pointed some tips you should be aware of :
    If you need that some funcionality of the class is derived by more than one "parent" then you should use interfaces, since you cannot extend more than one class.
    If your "superclass" needs to define some class variables then the choice must be made to have a superclass and then extend it. Also this is applicable if there is a method that can be programmed at a higher level (in interfaces you cannot program methods).
    But the answer to the question is still not easy. And remember, you can always mix both tipes, you can extend one class and implement some interfaces.
    Examples or that are very common in the Java API for AWT or Swing components, for example javax.swing.JLabel extends javax.swing.JComponent (that is beacuse a JLabel IS a JComponent and it uses some variables and methods programmed at the JComponent "level") and it also implements some interfaces: Accessible, ImageObserver, MenuContainer, Serializable & SwingConstants.
    I hope this helps.
    Zerjillo

  • Difference between Abstarct Class and Interface

    HI,
    Here is a simple one for the gurus but quite important for me.
    What is the difference b/w an Interface and an abstract class?
    Why do we need each one of them?
    I would appreciate if you people can give examples of each so that I amy understand fully
    Thanks in advance...

    A normal class (not abstract) has a special behaviour, like java.awt.Frame. A Frame is a frame no matter how you subclass it. If you create a subclass it will still be able to be displayed by calling it's show method. So by using a normal class you can create a type of class.
    An abstract class does the same, but it leaves some of the code unwritten. For instance java.lang.Number. This class is abstract becuase it has no knowledge of how to store the number in memory. But it knows that it is a number, and any subclass will still be a number. You could create a subclass of Number that can hold the time in milliseconds and checks your system clock to see what the time is, it could also have methods that return the time in another country, but it would still be just a Number.
    An interface is a way to describe what an object can do, not what it is. So with java.lang.Comparable as an example you can make any class comparable. This means that no matter what type of object you have, it can be compared with other objects. So you can have a subclass of Frame that can be compared with other windows. Or a subclass of Number that can be compared with other Numbers. You can even compare those two different types if you like. So you could compare a window with a number.
    That is the difference between abstract classes and interfaces.
    I hope you could follow my arguments, it isn't an easy subject,
    Daniel

  • Difference between abstact class and interface

    hi
    i am new in java.
    plz tell me abstract class support which type of polymorphisam and
    interface support which type of polymorphisam
    plz explain
    bye
    siva

    There's only one type of polymorphism.
    Does that make it mono-polymorphism? ;)
    Indeed - do a search for the forums.
    The short answer is that both abstract classes and interfaces define required method signatures for subclasses that extend/implement them, but abstract classes can have implementation for some or all methods that are not abstract; interfaces have no implementation whatsoever for any methods.

  • Difference between abstract class and the normal class

    Hi...........
    can anyone tell me use of abstract class instead of normal class
    The main doubt for me is...
    1.why we are defining the abstract method in a abstract class and then implementing that in to the normal class.instead of that we can straight way create and implement the method in normal class right...../

    Class vs. interface
    Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme. I use interfaces when I see that something in my design will change frequently.
    For example, the Strategy pattern lets you swap new algorithms and processes into your program without altering the objects that use them. A media player might know how to play CDs, MP3s, and wav files. Of course, you don't want to hardcode those playback algorithms into the player; that will make it difficult to add a new format like AVI. Furthermore, your code will be littered with useless case statements. And to add insult to injury, you will need to update those case statements each time you add a new algorithm. All in all, this is not a very object-oriented way to program.
    With the Strategy pattern, you can simply encapsulate the algorithm behind an object. If you do that, you can provide new media plug-ins at any time. Let's call the plug-in class MediaStrategy. That object would have one method: playStream(Stream s). So to add a new algorithm, we simply extend our algorithm class. Now, when the program encounters the new media type, it simply delegates the playing of the stream to our media strategy. Of course, you'll need some plumbing to properly instantiate the algorithm strategies you will need.
    This is an excellent place to use an interface. We've used the Strategy pattern, which clearly indicates a place in the design that will change. Thus, you should define the strategy as an interface. You should generally favor interfaces over inheritance when you want an object to have a certain type; in this case, MediaStrategy. Relying on inheritance for type identity is dangerous; it locks you into a particular inheritance hierarchy. Java doesn't allow multiple inheritance, so you can't extend something that gives you a useful implementation or more type identity.
    Interface vs. abstract class
    Choosing interfaces and abstract classes is not an either/or proposition. If you need to change your design, make it an interface. However, you may have abstract classes that provide some default behavior. Abstract classes are excellent candidates inside of application frameworks.
    Abstract classes let you define some behaviors; they force your subclasses to provide others. For example, if you have an application framework, an abstract class may provide default services such as event and message handling. Those services allow your application to plug in to your application framework. However, there is some application-specific functionality that only your application can perform. Such functionality might include startup and shutdown tasks, which are often application-dependent. So instead of trying to define that behavior itself, the abstract base class can declare abstract shutdown and startup methods. The base class knows that it needs those methods, but an abstract class lets your class admit that it doesn't know how to perform those actions; it only knows that it must initiate the actions. When it is time to start up, the abstract class can call the startup method. When the base class calls this method, Java calls the method defined by the child class.

  • Abstract class and interface????

    hi all, i would like to know the difference between abstract class and interface....could anybody enlighten me on this....

    Like the others have mentioned you can implement more than one interface, but only inherit from one abstract class. An abstract class can provide some implementation.
    steve http:\\www.jamonapi.com

  • Question about Classes, Abstract  Classes and Interfaces.

    I have been experimenting with Classes, Abstract Classes and Interfaces and wonder if anyone can explain this to me.
    I was looking for a way to assign a value to a variable and then keep it fixed for the session and have devised this.
    First I create an abstract class like this:
    public abstract class DatabaseConnection {
    private static String ServerName = null;
    public static void setServerName(String serverName) {
              ServerName = serverName;
         public static String getServerName() {
              return ServerName;
    }and then I created an interface
    public interface DatabaseAccess {
         String servername = DatabaseConnection.getServerName();
    }And finally the class itself with some test lines in it so I could see what was going on:
    public class CreateDatabase extends DatabaseConnection implements DatabaseAccess {
         public static void main (String args[]){
              new CreateDatabase();
         public CreateDatabase(){     
              setServerName("Server Name 1");
              System.out.println ("Before update ");
              System.out.println ("ServerName from Interface           = " + servername);
              System.out.println ("ServerName from Abstract Class = " + getServerName());
              System.out.println ("After update ");
              setServerName("Server Name 2");
              System.out.println ("ServerName from Interface           = " + servername);
              System.out.println ("ServerName from Abstract Class = " + getServerName());
              System.out.println ("==========================");
    }The output I get from the above is:
    Before update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 1
    After update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 2
    ==========================I also tried this in another class which calls the above class to see if I get the same effect
    public class CheckDatabaseAccess {
         public static void main (String args[]){
              new CreateDatabase();
              CreateDatabase.setServerName("Server 3");
              System.out.println("CreateDatabase "+CreateDatabase.servername);
              CreateDatabase.setServerName("Server 4");
              System.out.println("CreateDatabase "+CreateDatabase.servername);
              CreateDatabase.setServerName("Server 5");
              System.out.println("CreateDatabase "+CreateDatabase.servername);
    }The output of which is this:
    Before update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 1
    After update
    ServerName from Interface           = Server Name 1
    ServerName from Abstract Class = Server Name 2
    ==========================
    CreateDatabase Server Name 1
    CreateDatabase Server Name 1
    CreateDatabase Server Name 1Can anyone explain why I appear to only be able to change or set the ServerName only the once?
    Is this the correct way to do it? If it is it's exactly what I am looking for, a way to set the value of variable once in a session and then prevent it being changed.
    Or is there a better way of doing this.
    What I want to use this for is for example, storing the accesses to a database on a server. I won't know what server the database will be stored on nor what the database is called so I create an INI file which stores this information in encrypted format, which is set by the database administrator. It occurs to me I can use this method to then retrieve that data once and once only from the INI file and use that throughout the life of the session to access the database.
    Any help appreciated
    Regards
    John

    Not gonna read all of it, but this jumps out:
    public abstract class DatabaseConnection {
    private static String ServerName = null;
    public interface DatabaseAccess {
         String servername = DatabaseConnection.getServerName();
    }You have two completely separate variables (with two different names, for that matter, since you were inconsistent in your capitalization, but it wouldn't make a difference if they did have the same name with the same case). And the one in the interface is implicitly public, static, and final.
    Anytime you refer to "servername" through a reference of type DatabaseAccess, it refers to the one declared in the interface.
    Anytime you refer to "ServerName" inside the DatabaseConnection class, it refers to the one declared in that class.

  • What is the difference between document class and normal class

    Hi,
    Please let me know what is the difference between document class and normal class.
    And I have no idea which class should call as document class or call as an object.
    Thanks
    -Actionscript Developer

    the document class is invoked immediately when your swf opens.  the document class must subclass the sprite or movieclip class.
    all other classes are invoked explicitly with code and need not subclass any other class.

  • Difference between Conversion progs and INTERFACES

    Hi  plz     tell me  ...
    whats  the difference between    Conversion progs and Interfaces in ABAP .
    wat are  conversion progs  ( exmple) and interfaces  ( exmple ) ?
    thnks in advance....

    Hi
    CONVERSION programs are the ones which have one time usage, usually when a legacy system is being replaced by a system like SAP, then the data has to be mapped from the legacy system to SAP system. Here the data to be converted is given on a flat file & is uploaded to SAP tables mostly using LSMW only. Conversions programs are BDC,BAPI and LSMW programs in which you upload all the related tables from the flat files.Those are one time programs.
    Interface programs are those programs in which you fetch the data from the application server and process on theose data.These are helpful when you have to run any program in the backgroup when the presentation server is not working.
    INTERFACE programs are the ones which are run at regular intervals, say weekly, monthly or even daily. Here the legacy system continues to co-exist along with SAP system, the legacy system might be useful for certain functionalities but the data might have to run thru SAP transactions for complex data maintenance at regular intervals.
    In Simple
    CONVERSIONS : Converting Legacy System DATA into a flat file
    INTERFACES : Converting Flat File into SAP
    Conversion Program
    http://help.sap.com/saphelp_erp2005/helpdata/en/d3/a65a14e96911d1b401006094b944c8/frameset.htm
    Interface Program
    http://help.sap.com/saphelp_erp2005/helpdata/en/64/be5b4150b38147e10000000a1550b0/frameset.htm
    <b>Reward if usefull</b>

  • Difference between Data Class and Delivery Class

    What is the Difference between Data Class and Delivery Class , what happens Phisically to the Data .
    Moderator message: what is the difference between your question and a question that we'd welcome here in the forums?
    [Rules of engagement|http://wiki.sdn.sap.com/wiki/display/HOME/RulesofEngagement]
    Edited by: Thomas Zloch on Nov 22, 2010 1:17 PM

    What is the Difference between Data Class and Delivery Class , what happens Phisically to the Data .
    Moderator message: what is the difference between your question and a question that we'd welcome here in the forums?
    [Rules of engagement|http://wiki.sdn.sap.com/wiki/display/HOME/RulesofEngagement]
    Edited by: Thomas Zloch on Nov 22, 2010 1:17 PM

  • Difference between functional task and interface task

    Hi All,
    Kindly let me know the Difference between functional task and interface task when we create a task profile.
    Regards,
    Swetha

    Hi Sweta,
    The diferennce is Like we create different roles like store incharge and Store manager for Store manager there are list of activities that he can do like approve requests from store keeper and so on so these are Interface tasks as there are differences based on the roles of the employee but if a person can only create and not approve the transation then this is functional task difference

  • Difference between Material Class and Batch Class

    Hi!
    What is the difference between Material Class and Batch Class?
    and how can we use these classes?
    Rgds,
    Ajit

    Iam not sure but i think
    1) Material class for sorting purpose
    2) Batch Class for Batch Management
    thanks
    K.Prabakaran

Maybe you are looking for