Abstract Class X Interfaces

1.The Java language has two similar concepts : Abstract Classes and Interfaces. So, When its better to use one or other technique and the advantages and disadvantages of each one ?

Classes can implement any number of interfaces but can extend only one class. Interfaces are used when a class might want to implement that interface but extend another class. However, interfaces cannot have implementation, so that's what abstract classes are used for.

Similar Messages

  • Abstract class Vs interface

    Hi,
    I have to buid a report in ECM with complete details of the engineering as well as production. This include workflow as well as various fucntionality depends upon the criterion and user's event.
    I am implementating in OOPS and I Want to know that when I should use the Abstract class and when interface  ?
    Because as per me both serve the same purpose. Kindly send me the exact difference so that i can efficiently use the same.
    Thanks
    Prince

    When inheriting A Interface We have to inherit all the methods of the Interface there's no other option whereas with abstract classes we can inherit the members that we are in need of.
    Just the interface has to have body of the method and the method is to be used by the classes inheriting it. Whereas in the case of Abstract Class it can have declarations (Other than the abstract method) and it can be further extended in the classes inheriting the Abstract Class.
    Interface contains all abstract methods,all methods compulsory implemented by particular class, interface does not contain Constructor
    abstract classes are designed with implemantion gaps for sub-class to fill in.
    interfaces are sintacticlly similar to classes but they lack insance variables & methods.
    abstract classes can also have both abstract methods & non-abstract methods. where as in interface methods are abstract only, & variables are implicitly static&final
    regards
    Preetesh

  • 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

  • Abstract class and interface having same method

    Hello,
    Here is my problem. Suppose we have one abstarct class and one interface.Here is code-
    //Abstarct class
    abstract class X{
    abstract void myMethod();
    //Interface
    public interface Y{
    abstract void myMethod(){}
    Now i have a class which extends both abstarct class X and interface Y.
    If i call myMethod() from this class. Whose myMethod would be called.Will it be of abstract class or interface?
    Many Thanks

    Hello,
    Here is my problem. Suppose we have one abstarct class
    and one interface.Here is code-
    //Abstarct class
    abstract class X{
    abstract void myMethod();
    }OK, so far...
    //Interface
    public interface Y{
    abstract void myMethod(){}
    }An interface cannot have code (the {} part), so this won't work.
    Lets pretend though, it read
    //Interface
    public interface Y{
    abstract void myMethod();
    However, the abstract class above can have code;
    If you extended X and implemented Y (with no code in it), you would have to have a myMethod() implementation in your code. That's the one that would run.
    Now, let's pretend the abstract class above did have code in it.
    //Abstract class
    abstract class X {
    abstract void myMethod() { System.out.println("Hello"); }
    Then, you wouldn't have to have a myMethod() implementation in your class which extends X and implements Y (it's defined in X). If you didn't have one, the method in X would run. If you defined your own myMethod() implementation in your class (which extends X and implements Y), then your own implementation would run.

  • 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 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 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 vs Interface difference

    hi guys
    As such i know the basic difference ,but i want toknow what is the differnece between a interface and an abstract class with all the abstract methods in it.
    thanks a lot
    yash

    ,but i want
    want to know what is the differnece between a
    interface and an abstract class with all the abstract
    methods in it.You can view a class and an interface as being on the opposite extreme ends on a concrete-abstract scale.
    Say you start out with a fully concrete class. Just by adding the abstract keyword the class becomes abstract. You then remove implementation from this abstract class by making more and more methods abstract and finally you also make all methods public. You now basically have an interface. You just replace abstract class with interface and there you are.
    Basically Java wouldn't have to define an interface. The compiler could recognize and mark totally abstract classes as "interfaces" internally. The rules for extension would be that you can only extend one class carrying implementation. All other classes must be totally abstract. But admittedly, the system with declared interfaces is much more convenient for the programmer. You know up front just by looking at it that this "class" must stay totally abstract.

  • Abstract class Vs  Interface and importance of using

    Hi All,
    I want to know what is the difference between Abstract class and Interface.
    and what is the importance of using them.
    Moderator message: please search for available information/documentation.
    Edited by: Thomas Zloch on Sep 27, 2011 1:55 PM

    Please refer to this thread, already this is discussed in forums
    [ABAP Objects.. Abastract & Interface Class;
    Thanks
    Pavan

  • 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

  • Extend abstract class & implement interface, different return type methods

    abstract class X
    public abstract String method();
    interface Y
    public void method();
    class Z extends X implements Y
      // Compiler error, If I don't implement both methods
      // If I implement only one method, compiler error is thrown for not
      // implementing another method
      // If I implement both the methods,duplicate method error is thrown by 
      //compiler
    The same problem can occur if both methods throw different checked exceptions,or if access modifiers are different..etc
    I'm preparing for SCJP, So just had this weired thought. Please let me know
    if there is a way to solve this.

    Nothing you can do about it except for changing the design.
    Kaj

  • Object oriented design problem concerning abstract classes and interfaces

    I have an abstract class (class A) that takes care of database connections. It cannot be made into an interface as other classes extend it and all these other classes require the functionality in the methods it has (i.e. I cannot make all the methods abstract and then make this class an interface).
    I have a class that contains data (Customer class) that I will create from the data I extract from the database. This class will also be created by the User and submitted to the database portion of the program. The Customer class has functionality in its methods which is required by the rest of the program (i.e. I cannot make all the methods abstract and then make this class an interface).
    I have a factory class (CustomerFactory) that extends the Customer class. This has been created to restrict access to the creation and manipulation of Customers.
    I have a class (DatabaseQuery) that extends class A. But now that I have retrieved all of the information that comprises a Customer from the database, I cannot construct a Customer without making reference to UserFactory. But UserFactory is a class that I don't want the database portion of the program to know about.
    What I would like to do is have my DatabaseQuery class extend both Customer class and A class. But they are both classes and Java won't allow that.
    I can't make either of the two classes that I want to make parents of DatabaseQuery into interfaces... so what can I do other than just keep a reference to UserFactory in my DatabaseQuery class?
    Thanks,
    Tim

    >
    What I would like to do is have my DatabaseQuery class
    extend both Customer class and A class. But they are
    both classes and Java won't allow that.
    I can't make either of the two classes that I want to
    make parents of DatabaseQuery into interfaces... so
    what can I do other than just keep a reference to
    UserFactory in my DatabaseQuery class?Just a guess...
    The description sounds a little vague but it sounds like the correct solution would be to refactor everything. The first clue is when I see "database connection" as an "abstract class". The only hierarchy that a database connection might exist in is in a connection pool and even that is probably shaky. It should never be part of data records, which is what your description sounds like.
    That probably isn't what you want to hear.
    The other solution, which is why refactoring is better (and which also makes it apparent why the original design is wrong) is to create an entire other hierarchy that mirrors your current data hierarchy and wraps it. So you now have "Customer", you will now have "Customer" and "DBCustomer". And all the code that currently uses "Customer" will have to start using DBCustomer. Actually it is easier than that since you can simply make the new class be "Customer" and rename the old class to "DBCustomer". Naturally that means the new class will have to have all of the functionality of the old class. Fortunately you can use the old class to do that. (But I would guess that isn't going to be easy.)

  • Dealing with abstract classes and interfaces with XMLBeans

    I'm quite new to XMLBeans and would like some help. I've got things working when
    you are only saving concreate classes as XML, but when it comes to clesses containing
    interfaces I am running into problems.
    I basically have a collection of XY objects (see below) that I want to save as
    XML.
    I want to convert the following java classes to an xml schema:
    public class XY{
    X x;
    Y y;
    public interface X{
    void setA(int a);
    int getA();
    public interface Y{
    void setB(int b);
    int getB();
    public class X1 implements X{
    void setA(int a);
    int getA();
    //other data to save
    public class X2 implements X{
    void setA(int a);
    int getA();
    //other data to save
    public class Y1 implements Y{
    void setB(int b);
    int getB();
    //other data to save
    public class Y2 implements Y{
    void setB(int b);
    int getB();
    //other data to save
    What would be the best way to convert these to XML Schema? I've looked through
    all the XMLBeans documentation, but it doesn't say anything about dealing with
    interfaces/abstract classes. Is there anywhere else to look?
    Thanks in advance,
    Andrew

    Anurag,
    What I really wanted was a work-around to using substiutionGroups as substitution
    groups are not supported in this release.
    I want to convert the following schema:
    <xsd:complexType name="PublicationType">
    <xsd:sequence>
    <xsd:element name="Title" type="xsd:string"/>
    <xsd:element name="Author" type="xsd:string" minOccurs="0" maxOccurs="unbounded"/>
    <xsd:element name="Date" type="xsd:gYear"/>
    </xsd:sequence>
    </xsd:complexType>
    <xsd:complexType name="BookType">
    <xsd:complexContent>
    <xsd:extension base="PublicationType" >
    <xsd:sequence>
    <xsd:element name="ISBN" type="xsd:string"/>
    <xsd:element name="Publisher" type="xsd:string"/>
    </xsd:sequence>
    </xsd:extension>
    </xsd:complexContent>
    </xsd:complexType>
    <xsd:complexType name="MagazineType">
    <xsd:complexContent>
    <xsd:restriction base="PublicationType">
    <xsd:sequence>
    <xsd:element name="Title" type="xsd:string"/>
    <xsd:element name="Date" type="xsd:gYear"/>
    </xsd:sequence>
    </xsd:restriction>
    </xsd:complexContent>
    </xsd:complexType>
    <xsd:element name="Publication" type="PublicationType"/>
    <xsd:element name="Book" substitutionGroup="Publication" type="BookType"/>
    <xsd:element name="Magazine" substitutionGroup="Publication" type="MagazineType"/>
    <xsd:element name="BookStore">
    <xsd:complexType>
    <xsd:sequence>
    <xsd:element ref="Publication" maxOccurs="unbounded"/>
    </xsd:sequence>
    </xsd:complexType>
    </xsd:element>
    to produce an XML file like:
    <?xml version="1.0"?>
    <BookStore ¡Ä>
    <Book>
    <Title>Illusions: The Adventures of a Reluctant Messiah</Title>
    <Author>Richard Bach</Author>
    <Date>1977</Date>
    <ISBN>0-440-34319-4</ISBN>
    <Publisher>Dell Publishing Co.</Publisher>
    </Book>
    <Magazine>
    <Title>Natural Health</Title>
    <Date>1999</Date>
    </Magazine>
    <Book>
    <Title>The First and Last Freedom</Title>
    <Author>J. Krishnamurti</Author>
    <Date>1954</Date>
    <ISBN>0-06-064831-7</ISBN>
    <Publisher>Harper & Row</Publisher>
    </Book>
    </BookStore>
    What is the best way to do this without using substitution types?
    Thanks,
    Andrew
    "Anurag" <[email protected]> wrote:
    Andrew,
    Could you please paste/attach a sample of the code you are using to convert
    Java bean classes to XMLBeans?
    In the current release the goal of XMLBeans technology was to convert
    from
    XML Schemas or XML files to XMLBeans. The focus was not towards conversion
    of Java beans to XMLBeans.
    Regards,
    Anurag
    "Andrew" <[email protected]> wrote in message news:[email protected]...
    I'm quite new to XMLBeans and would like some help. I've got thingsworking when
    you are only saving concreate classes as XML, but when it comes toclesses
    containing
    interfaces I am running into problems.
    I basically have a collection of XY objects (see below) that I wantto
    save as
    XML.
    I want to convert the following java classes to an xml schema:
    public class XY{
    X x;
    Y y;
    public interface X{
    void setA(int a);
    int getA();
    public interface Y{
    void setB(int b);
    int getB();
    public class X1 implements X{
    void setA(int a);
    int getA();
    //other data to save
    public class X2 implements X{
    void setA(int a);
    int getA();
    //other data to save
    public class Y1 implements Y{
    void setB(int b);
    int getB();
    //other data to save
    public class Y2 implements Y{
    void setB(int b);
    int getB();
    //other data to save
    What would be the best way to convert these to XML Schema? I've lookedthrough
    all the XMLBeans documentation, but it doesn't say anything about dealingwith
    interfaces/abstract classes. Is there anywhere else to look?
    Thanks in advance,
    Andrew

  • Abstract Classes VS Interfaces

    What is the use of an abstract class when we have interfaces?As far as i know abstract classes cannot be inherited and yes they do provide you the facility of implementing all or some of the concrete methods defined in them.Can anyone define this concept please

    LOL :)
    Anyway, it is very common to have a situation where some classes have a lot in common, but not everything...
    You can use an abstract class to do the common things, and define abstract methods for the things the overriding classes must implement themselves...
    public abstract class SomeClass {
        public void doCommon() {
            System.out.println("All classes should print this line :)");
        public abstract void doSpecific();
    }

  • Abstract Classes versus Interfaces

    Somebody at work has just made an interesting observation and its bugging me, comments please.
    When I started Java I just used classes (and abstract classes), and didnt bother with Interfaces I understood them to be a way of getting round the lack of MultipleInheritance and it wasnt a problem that concerned me.
    But as time went on I found that sometimes I did want classes that had little in common to provide some additional feature (such as logging), and interfaces were great for this.
    ..so I was happy ..
    During all this time if I want a HashSet I would write code like this
    HashSet dataSet = new HashSet();but then I read that HashSet was an implementation detail and we should be using Interfaces as follows:
    Set dataSet = new HashSet();So whereas before I might have had a class hierachy with an Abstract class at the top , I started slotting in Interfaces above that and viewing the Abstract class as just a convenience to implementing the Interface.
    So which is the right method , originally I saw subclassing object as an 'is a ' relationship and implementing an interface as a 'implements' relationship. But more recently it seems to be turned on its head and implementing an interface is an 'is a' relationship (but supports multiple inheritance)
    Also it seems to be the trouble with this second approach is that anyone can implement an interface, for example I could implement Set,Map and List with one class, the class hierachy is not so helpful .

    Thanks, but the question was alot wider than that,
    the HashSet example was just one part of it.I think it is representative of all the situations that you talk about, which are whether an instantiator should handle the instantiated object by its interface or by its implementation.
    I suppose the question is
    "How do you code model "is a " relationship in java
    through extending a class or creating an interface
    and implementing it"
    MySubClass extends MySuperClass implements MyInterface {}MySubClass is a MySuperClass and a MyInterface. The way that I view it, the "is a" relationship applies to all type inheritance, even for the multiple type inheritance that you can have with interfaces. The "is a" relationship doesn't doesn't have to be a 1:1 mapping. There's no point in thinking about it differently since that's how the language behaves.
    an alternative question is
    "is it correct to mix/match both methods I described
    above"I thought I gave an answer. You said that my answer is not "broad enough." How so? My answer was that handling an object that you instantiate by its interface can reduce the amount of changes you have to make if you change the implementation. You will have to make one change (the line of code that instantiates the object) instead of many. Also, handling it by its interface makes it easier to switch from object A instantiating object B to object A being passed a reference to B and to object A getting its dependencies injected by XML configuration.
    It seems weird to handle an object by its interface if you already know it's implementation, but it's commonly seen and this is why I think it must be used. As I said, it's a small benefit of abstraction.
    The times when you may not want to do this is when the instantiator has to call methods from different interfaces of the object. You can handle it by its interface by casting between the different interfaces you have to work with, or you can just handle it by its implementation, gaining access to all of the object's interfaces.
    Note that everything I explained concerns the type by which the instantiator handles an instantiated object. If a class does not instantiate a certain object, then it almost always should receive it by its interface, unless it's some really common implementation that's never going to change.
    I use interface, abstract class, and base class interchangeably. It's up to you to decide which to use for type inheritance. It's good practice to favor interfaces.

Maybe you are looking for

  • CS3 Upgrade & Camera Raw 4.5 = MAJOR HEADACHE!

    I bought a D300. Then found out that the only way to use Photoshop with it was to upgrade the Camera Raw plug-in to 4.5, which could ONLY be used with CS3. So NOW I have THOUSANDS of dollars in camera gear and software that has caused me more headach

  • Alphabet Soup

    I just bought a flat panel monitor. It has two connection ports. VGA and DVI-D. Yippee, I think. I won't need the video switcher I bought that hasn't arrived yet. (To switch between a really old WinXP desktop and the Macbook when I want to use an ext

  • Using Variables in Query generator

    I'm using the following query to pull a report together later to be used in a query print layout. When i specify the specific part number and customer code it returns what i expect but as soon as i add a variable it says "Must specify table"! SELECT

  • How to load the data in DSO

    Hello,          In my BI system ,i have the DSO and InfoCube ,haveing the infopackage Delta and Init..can any one tell me how to load the data from R/3 in to DSO ,when we have two infopackage(one is delta nad other is Init).Please define brifly.

  • Indesign 5 (7.0.4)

    I can no longer delete anything using delete key.  My only option is go to edit, clear.  Is anyone else experiencing this problem?  The delete works fine in all other CS 5 products. Any  thoughts?