When we will go for an abstract class and when we will go for an interface?

it's always some what confusing to choose an abstract class and an interface,can anybody post a suitable answer for this.

jwenting wrote:
with experience and the insight it brings, you will know which to use when.
Without it, it can't be explained.
More often than not there's no X OR Y anyway.It's fortunate that there are posters here who possess the insight and experience necessary to explain this. The principal differences between an abstract class and an interface are,
1. An abstract class can carry implementation, whereas an interface cannot.
2. An abstract class is singly inherited, wheras an interface is multiply inherited.
So use an abstract class when the implementation it can carry outweights the fact that it cannot be multiply inherited That's the gist of it.
The inheritance relationship where this happens is when the supertype is a general concept of which all potential subtypes are special cases. This is called a specialization (or sometimes a generalization) relationship. For example Apple and Banana are Fruit. Or Car and Bike are Vechicle. The Fruit and Vechicle supertypes are general concepts of which their subtypes are special cases. In this case make Fruit and Vechicle abstract classes because the subtypes will benefit from a shared implementation.
If you don't have a clearcut specialization/generalization relationship make the supertype an interface. An example could be the Comparable supertype. The potential subtypes aren't supposed to be specializations of the Comparable concept, they're suppose to become Comparable (and make this property an integral part of their being). This is not a specialization/generalization relationship. Instead the supertype is intended to add character to the subtypes. The subtypes are unlikely to benefit from an inherited implementation. So make Comparable an interface.

Similar Messages

  • 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

  • How do I reorder songs in a playlist in the new itunes??? I can no longer just click and drag. When I click, it doesn't move!!!! Need help ASAP- trying to prepare for an aerobics class and need songs in a specific order!

    How do I reorder songs in a playlist in the new itunes??? I can no longer just click and drag. When I click, it doesn't move!!!! Need help ASAP- trying to prepare for an aerobics class and need songs in a specific order!

    Vera,
    Use View > View Options, and set 'Sort By" to "Manual Order."
    Then you will be able to drag-n-drop songs up and down the list.

  • Why when i want to download a free app from app store it asks for my apple id and when i give my apple id it then says "this apple id has not yet been used in the itunes store". i dont even know what that means and it will this happen everytime?

    why when i want to download a free app from app store it asks for my apple id and when i give my apple id it then says "this apple id has not yet been used in the itunes store". i dont even know what that means and it will this happen everytime?

    If you are within 14 days of purchase you can still return the iPhone and get the phone that suits your needs, however, I think you will find that no matter which phone you get the content provider will want to know how you are going to pay for future purchases. For Android phones it is Google, and they will certainly want to know.
    To create an Apple account without a credit card see: http://support.apple.com/kb/HT2534

  • Hello. I have adobe forms and received the alert that it will be ending in July. Then I received an email about Adobe Acrobat XI Pro which can create forms. I signed up for the free trial and when I began to make a new form it brings me back to Adobe Form

    Hello. I have adobe forms and received the alert that it will be ending in July. Then I received an email about Adobe Acrobat XI Pro which can create forms. I signed up for the free trial and when I began to make a new form it brings me back to Adobe Forms. My question is, when Adobe Forms ends on July 28th will Adobe Acrobat XI Pro be able to create forms or will it now? and if not, then why is adobe advertising for it still?

    What you're calling "Adobe Forms" is really Adobe FormsCentral. The FormsCentral service is indeed going away soon, but you can always create PDF forms (AcroForms) with Acrobat. Acrobat also comes with a desktop version of the FormsCentral desiger, which can be used to create simple PDF forms that can be used apart from the FormsCentral service. So you'll no longer be able to create and host web forms with the FormsCentral service or use PDF forms with the FormsCentral service. You will be able to create standalone PDF forms with Acrobat and simple PDF forms with the FormsCentral desktop app.

  • I have just gone from PCM to MacBook Pro retina and would like to now go to imac. Is it worth waiting for retina on imac and when will it arrive

    I have just gone from PCM to MacBook Pro retina and would like to now go to imac. Is it worth waiting for retina on imac and when will it arrive

    I'm not Klaus but can give an opinion on this part:
    As a Mac man yourself do you think that the retina display is worth waiting for? 
    I'm 65, have used Macs since 1989, and struggle with displays, cataracts, and bifocals. What I've seen of the Retinas in stores is that text size gets sacrificed for image quality. There are quite a few complaints about Retina in the MacBook Pro forums about not being able to increase the size of menu text without it getting fuzzy.
    My iMac 27-inch is about a year old and I can set the display res from its default of 2560x1440 to 1920x1080 and everything is sharp. I understand that handy trick will not work for either the older hi-res macbook pros or the Retinas, so I don't expect it for any other Macs.
    Speculation on Apple policy and new product releases is actiually not allowed by the Terms of Use around here so I doubt you'll get an answer to the "when" part. Anyone who does answer "when" is either guessing it up or violating a non-disclosure agreement!   Apple plays its cards close to its vest and we average users only know "when" when Apple posts the announcement.

  • My contacts will not appear on my computer and when I go to the webpage for Icloud, it says that I can't connect to the server.

    My contacts will not appear on my computer and when I go to the webpage for Icloud, it says there is an error and that I can't connect to the server. (which may have something to do with the facts that my contacts have disappeared.)

    giddeonsmom wrote:
    i have a iphone 3g i have been tryin for 2 hours to sync the music on my phone to a new computer without it erasing everything. can someone please help me
    The iphone is not a storage device.
    The music sync is one way - computer to iphone.  The exception being itunes purchases.
    You need to copy everything from the old computer, or your backup copy of your old computer, to the new one.

  • My phone will randomly disconnect from the wifi and when I retype the password it says it is wrong. It will eventually work but I have to wait for a message to pop up on my screen to allow me to retype the wifi password.

    When I first got my phone it worked perfectly fine with the wifi. Although later on I began to have problems connecting it. It will randomly disconnect from the wifi and when I try to retype the password it tells me it is wrong, although it is right. It will eventually work but in its own time, a message will pop up and allow me to type in the password and it will work. But sometimes it takes an hour or more and sometime it takes 10 minutes. I've seen where other people have had this problem but I don't know how to fix it. I'm not sure if it's an issue with my phone or if it's with my wifi. Does anyone know how to fix this?

    Does this happen with all Wi-Fi hotspots?  A specific one?
    Have you tried forgetting the Wi-Fi connection and then reconnecting to it?
    What about power cycling the Wi-Fi router?

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

  • Question about abstract classes and instances

    I have just read about abstract classes and have learned that they cannot be instantiated.
    I am doing some exercises and have done a class named "Person" and an abstract class named "Animal".
    I want to create a method in "Person" that makes it possible to set more animals to Person objects.
    So I wrote this method in class Person and compiled it and did not get any errors, but will this work later when I run the main-method?
    public void addAnimal(Animal newAnimal)
         animal.add(newAnimal);
    }Is newAnimal not an instance?

    Roxxor wrote:
    Ok, but why is it necessary with constructors in abstract classes if we don�t use them (because what I have understand, constructors are used to create objects)?Constructors don't create objects. The new operator creates objects. An object's c'tor is invoked after the object has already been created. The c'tors job is to initialize the newly-created object to a valid state. Whenever a child object is created, the parent's c'tor is run before the child's c'tor, so that by the time we're inside the child's c'tor, setting up the child's state, we know that the parent (or rather the "parent part" of the object we're initializing) is in a valid state.
    Constructor rules:
    1) Every class has at least one ctor.
    1.1) If you do not define an explicit constructor for your class, the compiler provides a implicit constructor that takes no args and simply calls super().
    1.2) If you do define one or more explicit constructors, regardless of whether they take args, then the compiler no longer provides the implicit no-arg ctor. In this case, you must explicitly define a public MyClass() {...} if you want one.
    1.3) Constructors are not inherited.
    2) The first statement in the body of any ctor is either a call to a superclass ctor super(...) or a call to another ctor of this class this(...) 2.1) If you do not explicitly put a call to super(...) or this(...) as the first statement in a ctor that you define, then the compiler implicitly inserts a call to super's no-arg ctor super() as the first call. The implicitly called ctor is always super's no-arg ctor, regardless of whether the currently running ctor takes args.
    2.2) There is always exactly one call to either super(...) or this(...) in each constructor, and it is always the first call. You can't put in more than one, and if you put one in, the compiler's implicitly provided one is removed.

  • 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

  • Abstract class and RMI

    Hi!
    I have a desgin where I have an abstract class that in its constructor registers itself in a registry and define three abstract methods. Then I have a class that extends the abstract class and implements the three methods.
    One of the methods inserts som text in a textArea defined in the child of the abstract class but when I call this method remotly I get a nullpointer exception saying that the textArea has not been initialized. The child ofcause calls super in its constructor.
    So my question is can you not extend an abstract class that register it self in the constructor and then call methods remotly that uses variables that have been initialized in a childs constructor?
    Have your any idea to why I get the nullpointer exception?
    Peter

    >
    This sounds like there might be a misunderstanding
    about the nature of methods and variables. If, for
    instance, your client looks something like this:
    RObject roo = ...// get via RMI
    TextArea text = roo.getTextArea();
    text.setText("...");
    My design is more like this:
    public interface Subscriber extends Remote {
      public void notifySubscriber();
    public abstract class A implements Subscriber {
      a() {
        server.addSubscriber(this);
      public abstract method1();
      // some more abstract methods
      public void notifySubscriber() {
        // do some stuff
        method1();
    public class B extends A {
      JTextArea text;
      A() {
        super();
        text = new JTextArea();
      public void method1() {
        // do some stuff
        // then text is null when called remotly
        text.setText("Hello");
    }Hope this makes my design more clear and you can see the problem.
    Thanks in advance

  • Concrete classes implement abstract class and implements the interface

    I have one query..
    In java collection framework, concrete classes extend the abstract classes and implement the interface. What is the reason behind extending the class and implementing the interface when the abstract class actually claims to implement that interface?
    For example :
    Class Vector extends AbstractList and implements List ,....
    But the abstract class AbstractList implements List.. So the class Vector need not explicitly implement interface List.
    So, what is the reason behind this explicit definition...?
    If anybody knows please let me know..
    Thanx
    Rajendra.

    Why do you post this question again? You already asked this once in another thread and it has been extensively debated in that thread: http://forum.java.sun.com/thread.jsp?forum=31&thread=347682

  • Abstract classes and OO theory...

    I have an OO theory question related to abstract classes and their member variables. I realize opinions will vary from person to person but I'll ask anyway...
    If I'm creating an abstract class, should member variables that will be used by subclasses be private or protected? Why? Either way, they will have accessor methods for classes that instantiate them (where appropriate) but I'm debating whether or not to give subclasses direct access to these variables or not.
    To me, it seems odd to make variables in the abstract class private but I'm curious what your opinions are.
    Thanks...

    I knew you'd say that. I'd like to play along with a for-instance, if you will allow ... here's an example parent class:
    public abstract class ProvideMenu   extends JFrame {
      protected              JMenuBar       jmbar;
      protected              JMenu          jmfile,
                                            jmedit,
                                            jmhelp;
      protected              JMenuItem      jmfnew,
                                            jmfopen,
                                            jmfsave,
                                            jmfsaveas,
                                            jmfprint,
                                            jmfexit,
                                            jmecopy,
                                            jmepaste,
                                            jmhabout,
                                            jmhcontents;
      public ProvideMenu() {
        jmbar       = new JMenuBar();
        jmfile      = new JMenu( FILE_MENU );
        jmedit      = new JMenu( EDIT_MENU );
      public abstract void aMeth();
    }Now the subclass does not need to provide setProvideMenuFont( new Font( ... ) ) and Font getProvideMenuFont() methods, setProvideMenuEnabled(), etc. but can use the standard methods setFont, getFont setBackground(), setEnabled, etc, etc.
    Mind you I'm not advocating this ... what I am doing is trying to open the discussion up a bit - I hope no one minds ... what better design - just a for-instance - would you advocate?
    ~Bill

  • Abstract class and class

    What is the difference between abstract class and class in java?

    arcadesstuff wrote:
    Abstract class: a class that contains at least one abstract method. As has already been mentioned, abstract classes need not contain any methods at all. Have a look at the abstract class you posted; it's still abstract, though it contains no abstract methods. Note that if one declares any method of a class abstract, the class itself must be declared abstract as well.
    When you implement the abstract class Animal, you will have to write the code of those two abstract methods from above.Your example contains no abstract methods. Abstract methods must be marked with the keyword "abstract".
    ~

Maybe you are looking for

  • After effects cs5.5 error

    Hi everione, can you please helpe me!! I just installed the adobe after effects cs5.5 and when i startup the program it says "After Effects error: Crash in progress. Last logged message was: <4532> <AppDirs> <5> Required Dir= C:\Program Filles\Adobe\

  • Where can I learn about the 'Base Warranty of Depot Service"

    There is a default warranty of one year with new T61 called 'Depot Service' Where can I learn more about it, what it covers and how does it work ?

  • Drop down list for a field in table maintainance

    Hi, I have created a table maintainance for ztable. I need a drop down list for field so that user can select values present in the list while giving entries. I can not use fixed values in domain, because feild length is more and it wont fit into fix

  • Extended Classic PO output pass to R3 ?

    1. Extended classic Purchase Orders are fully approved (no approval required workflow) in SRM - status "HELD" 2. When we process PO and "order" - the PO is transmitted to R/3 (great, everything seems to be there). 3. There are no messages associated

  • Why itunes is automatic changing my genre to chinese when I play my songs?

    What is happening to my itunes? Every time I play a song the language of my genre just automatic change to chinese without infrom me anything. I've organized all the songs by the genres and also use genres to creat playlists for my ipod, but now they