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.

Similar Messages

  • 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

  • Why interfaces why not abstract classes?

    why they are using interfaces concept in JDBC or struts2.0 why not abstract classes?
    thanks in advance.

    user5287726 wrote:
    jverd wrote:
    user5287726 wrote:
    Interfaces are more flexible. For certain definitions of flexible, yes, but not for others.
    A Java class can only inherit one class, but it can implement multiple interfaces.Which has absolutely nothing to do with why JDBC declares interfaces rather than abstract classes.How does your post even attempt to answer the OP's question?OP asked: "why they are using interfaces concept in JDBC or struts2.0 why not abstract classes?" I'm pointing out that your post does not address the question asked. And of course your answer is wrong anyway.
    As for addressing the OP's question, I did that in my first response.

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

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

  • 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

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

  • Why use Factory classes

    Why do we use Factory classes such BorderFactory, to get an instance of Border class, why cant we directly create an object of such classes like we do with regular concrete classes

    Why do we use Factory classes such BorderFactory, to
    get an instance of Border class, why cant we directly
    create an object of such classes like we do with
    regular concrete classesFactory methods (I mean static create methods here) have two advantages.
    First, the library designer doesn't have to expose concrete classes to the outside world, just interfaces. This adds flexibility.
    Second, the library designer is free to make object creations more flexible. The create method may take parameters that doesn't exactly correspond to a constructor of one specific class.

  • 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

  • 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

  • Why Use Nested Classes

    Hi All,
    Why do we use Nested Classes ? Explain it with example ....
    If we say - It is a way of logically grouping classes that are only used in one place. Then we can say we use it through "Package" so why inner class ??
    Thanks in advance ....

    A real life example to jschell's explaination may be this.
    The pistons in your automobile engine are encapsulated by the engine block -- or the engine block encapsulates the pistons inside. This is the desired effect because as soon as we take the pistons out of the engine block, and put them say, in the backseat of the car instead, they no longer perform the function they were intended. There is another side effect to this analogy. When the pistons are properly installed in the engine block, there is only one movement the pistons can move -- up and down movement, that's it... they cannot rotate, spin, twist around or anything inside the engin block. Furthermore, the up and down movement is the only useful thing a piston can do. As soon as we throw the pistons in the backseat of the car, they can roll around, spin, and generally rotate to any configuration or orientation -- which does not produce any useful power.
    Inner classes are generally the same way. So we can see this example with a little code -- which we like.
    public class Engine
      Piston[] pistons = new Piston[8];
      class Piston
        // the usual methods here..
    }Of course, if your program is extremely sohisticated, this may not be a good solution -- for example, if you are making a catalog of automotive parts, then you would probably want your <tt>Piston</tt> class to be stand-alone.
    Edited by: pierrot_2. Also notice that the class <tt>Piston</tt> is not an INNER class of Backseat!

  • Why use helper classes?

    I am confused about the purpose of helper classes when using EJB's. Is the idea simply to make the code more maintainable? To separate data access code from the business logic? To aid the reuse of code? Why should I choose to use a helper class rather than creating a new EJB to do the job?
    I have been unable to find any comprehensive articles, and am a bit confused!
    Thanks in advance.

    - split out code into distinct functional models
    - split out code that can be reused effectively elsewhere
    - wrap objects that need to be passed to other modules as a whole
    - performance (EJBs are slow compared to standard beans)
    - keep code shorter (per file/method) so it's easier to read and maintain
    etc. etc.

  • Why how Abstract class   for java.util.set

    I need to use Set i din't find any impelemnted class for Set, i don't want HashSet or LinkedHashSet just a Set is enough for my purpose.
    How can i take instance of AbstractSet it is abstract.....
    Is the only way is to write my own class extending AbstractSet.
    Or is there something which i'm missing
    TIA Nas

    Because Vector isn't an ancsetor of AbstractList.
    What you are trying to do is the same as saying that becasue my cousin and I have the same grandfather we must have the same parent which isn't true.
               Collection
            Set         List
       AbstractSet      AbstractList
       HashSet              Vector

  • Without Subclass we don't Use Abstract Class?

    It Correct or Not?
    Explain correct answer?

    Hello MengyaLiu, and welcome to the forum,
    I’m honestly not sure why our delivery team would have told you they were on their way to your home and then not arrive without an explanation as to why. Our delivery agents should be notifying you of all necessary changes in their delivery schedules, as we realize the inconvenience any possible delay may cause, so it’s regrettable to hear we failed you in this regard. I truly apologize for any frustration this oversight may have caused.
    While I’ve personally documented your feedback here at the corporate office to ensure something of this nature doesn’t happen in the future, I’m glad to hear our delivery team was able to make this right and successfully delivered your TV yesterday. Please feel free to let us know how it went and if you have any further questions for me. I’ll be glad to help.
    Best wishes,
    Alex|Social Media Specialist | Best Buy® Corporate
     Private Message

Maybe you are looking for

  • Mac OS X Update Combined 10.5.8 won't install

    I downloaded the OS X update for 3 hours...when it was about to install it said that apple must have changed something because it won't install. i forgot what the whole dialogue box said but it was something like that. how do i update my OS if it won

  • Anyone know how to fix this error: RROR ITMS-9000: "OPS/ibooks.ncx(5): element "content" not allowed yet

    Trying to publish an iBook and having major problems at the last step.  Here is my error message: Apple's web service operation was not successful                     Unable to authenticate the package: B_SPACE_NUTRITION.itmsp                     ERR

  • Setup of PRE & PSE V12 fails repeatedly even after reboot

    I have a working installation of Lightromm 5.3 Photoshop Elements V11 Premiere Elements V11 on a Windows 7 SP1 PC. After purchasing a new licenes of PSE&PRE V12 succesfully downloaded and unpacked all files. but Setup process fails even after reboot

  • Can BC Generate an invoice with the customers payment information without actually processing it.

    I am trying to set up our E-shop using BC. We have a very ancient Point of sales/Inventory system so to sync our system with BC wouldn't be possible so what I would like to do is use BC E-commerce system to generate invoices and collect the payment i

  • Use of Adobe programs

    Hi, I'm thinking about buying the hp 15-r117na notebook, however I will mostly be using it for graphic design using Adobe photoshop and illustrator. The laptop has 8gb ram and 1tb storage which is good, but I don't know what other details I need to l