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

Similar Messages

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

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

  • Why are we using Abstract class?

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

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

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

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

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

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

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

    repost to pique interest

  • Using List Class in java.awt / java.util ?

    have a program that:
    import java.util.*;
    List list = new LinkedList();
    list = new ArrayList();
    ... read a file and add elements to array
    use a static setter
    StaticGettersSetters.setArray(list);
    next program:
    import java.awt.*;
    public static java.util.List queryArray =
    StaticGettersSetters.getArray();
    If I don't define queryArray with the package and class, the compiler
    gives an error that the List class in java.awt is invalid for queryArray.
    If I import the util package, import java.util.*; , the compiler
    gives an error that the list class is ambiguous.
    Question:
    If you using a class that exists in multiple packages, is the above declaration of queryArray the only way to declare it ?
    Just curious...
    Thanks for your help,
    YAM-SSM

    So what you have to do is explicitly tell the compiler which one you really want by spelling out the fully-resolved class name:
    import java.awt.*;
    import java.sql.*;
    import java.util.*;
    public class ClashTest
        public static void main(String [] args)
            java.util.Date today    = new java.util.Date();
            java.util.List argsList = Arrays.asList(args);
            System.out.println(today);
            System.out.println(argsList);
    }No problems here. - MOD

  • Using ExecutorService class from java.util.concurrent package

    Dear java programmers,
    I have a question regarding the ExecutorService class from java.util.concurrent package.
    I want to parse hundreds of files and for this purpose I'm implementing a thread pool. The way I use the ExecutorService class is summarized below:
    ExecutorService executor = Executors.newFixedThreadPool(10);
            for (int i = 0; i < 1000; i++){
                System.out.println("Parsing file No "+i);
                executor.submit(new Dock(i));
            executor.shutdown();
            try {
                executor.awaitTermination(30, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            executor.shutdownNow();However, the code snippet above creates all the 1000 threads (Dock objects) at once and loads them to the executor, and thus I'm worrying about memory leak. I haven't tested it on 1000 files yet but just on 50 small ones, and even if the program prints out "Parsing file No "+i 50 times at once, it executes normally the threads in the background.
    I guess the write way would be to keep the number of active/idle threads in the executor constant (lets say 20 if the thread pool's size is 10) and submit a new one whenever a thread has been finished or terminated. But for this to happen the program should be notified someway whenever a thread is done. Can anybody help me do that?
    thanks in advance,
    Tom

    Ok I found a feasible solution myself although I'm not sure if this is the optimum.
    Here's what I did:
            ExecutorService executor = Executors.newFixedThreadPool(10);
            Future<String> future0, future1, future2, future3, future4, future5, future6, future7, future8, future9;
            Future[] futureArray = {future0 = null, future1 = null, future2 = null, future3 = null, future4 = null, future5 = null,
            future6 = null, future7 = null, future8 = null, future9 = null};
            for (int i = 0; i < 10; i++){
                futureArray[i] = executor.submit(new Dock(i));
            }I created the ExecutorService object which encapsulates the thread pool and then created 10 Future objects (java.util.concurrent.Future) and added them into an Array.
    For java.util.concurrent.Future and Callable Interface usage refer to:
    [http://www.swingwiki.org/best:use_worker_thread_for_long_operations]
    [http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Java/Chapter10/concurrencyTools.html]
    I used a Future[] Array to make the code neater. So after that I submitted -and in this way filled up- the first 10 threads to the thread pool.
            int i = 9;
            while (i < 1000){
                for (int j = 0; j < 10; j++){
                    if (futureArray[j].isDone() && i < 999){
                        try{
                            i++;
                            futureArray[j] = executor.submit(new Dock(i));
                        } catch (ExecutionException ex) {
                            ex.printStackTrace();
                        } catch (InterruptedException ex) {
                            ex.printStackTrace();
                try {
                    Thread.sleep(100); // wait a while
                } catch(InterruptedException iex) { /* ignore */ }
            executor.shutdown();
            try {
                executor.awaitTermination(60, TimeUnit.SECONDS);
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            executor.shutdownNow();
        }Each of the future[0-9] objects represents a thread in the thread pool. So essentially I'm check which of these 10 threads has been finished (using the java.util.concurrent.Future.isDone() method) and if yes I replenish that empty future[0-9] object with a new one.

  • 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

  • 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

  • Abstract classes in jave.i0

    I have read that you cannot create and instance of an abstract class. If that is correct how is it possiable that I can code this ?
    File Myfile = new File('c:/abc.txt);
    What am I missing can anyone help ?

    Ohh, wait, got it.
    java.io.File An abstract representation of file and directory pathnames.
    It is not an abstract class, if you look at an abstract class AbstractList for example, it will say "abstract class AbstractList" in the API.
    File however takes a concept common (but not necessary identical) to all operating Systems (like Windows, Linux and MacOS X), but "abstracts" it, so you the developer are not exposed to the differences between OSes.

  • 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

  • Problems changing colour using Graphics class in java.awt

    Hi,
    The problem only happens when more than two images are on a panel. In this case, I have to strings that are drawn. The first drawn string is called "A" the second drawn string is called "B". However, when i change the colour of "B" to let's say Red, the panel erases the letter "B" and insteads changes "A" to red. How can I fix this so that when the user chooses the colour red it changes the colour of the latest drawn string and not the first one. please help!!!!
    import java.awt.*;
    public class StringPanel extends GBPanel
         private String shape = "clear", str;
         private int x, y;
         private Color color = Color.black;
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              g.setColor (color);
              if(shape.equalsIgnoreCase("draw string"))
                   g.setColor(color);
                   g.drawString(str, x, y);
              else if (shape.equalsIgnoreCase("exit"))
                   System.exit(0);
         public void drawCurve(Color color)
         this.color = color;
         repaint();
         public void drawString(String shape, String str, int x, int y)
              this.shape = shape;
              this.str = str;
              this.x = x;
              this.y = y;
              repaint();
         public void drawString1(String shape, String str, int x, int y)
              Graphics g = getGraphics();
              g.setColor(color);
              if (shape.equalsIgnoreCase("draw string"))
                   g.setColor(color);
                   g.drawString(str, x, y);
              else
                   repaint();
    }

    well, as I said, I can't remember what the update method thing was for... I think it was related to not clearing the screen first.
    Anyway, if you maintain a list of objects that should be drawn and then in the paintComponent method, loop thru the list of objects and redraw them, it will work. Then you change the state of an object and call repaint. When you are going to change color, you need to, in effect, redraw the entire affected area. Now this can be done partially with clipping, but it's complicated to deal with that. So the simplest way is just redraw everything on repaint.

  • Using C++ classes in Java

    I need links, ebooks or other resources of using C++ in Java using JNI.
    regards!

    Yes! I have understand it.
    Now I am reached to this link http://www.javaworld.com/javaworld/javatips/jw-javatip17.html?page=2
    void NumberListProxy_initCppSide(struct HNumberListProxy* Obj);
    the method signature is different from the one that is generated here at my machine by java which is:
    JNIEXPORT void JNICALL Java_NumberListProxy_initCppSide
    (JNIEnv *, jobject);
    Also when I run the command ' javah stubs NumberListProxy '
    Error: JNI does not require stubs, please refer to the JNI documentation.
    I think u ( bschauwejava ) can tell me about this problem.

Maybe you are looking for

  • Blue Screen of Death Problem

    Hi, I have a Toshiba Satellite L455D-S5976 with Windows 7 Home Premium and a 32-bit operating system. I've been having problems with getting BSODs for well over a month now (I was out of town for most of it), sometimes within a couple minutes of rest

  • Loaded atv 4.2.2 problem with netflix login.  Has anyone solved this problem?

    Cannot login to Netflix on Apple TV after the 4.2.2 update.  Ihave done a restore, unplugged and restarted, called netflix and they changed password.  Was able to login to Netflix on Mac Air.  Netflix says call apple.

  • Excise tb not seen in MIGO

    hi all, for cenvat material for which GR already done for many time for same vendor with capturing all excise duties, but now it is not showing excise tab while migo. How  it is possible & why it is happen ? i check all necessary entrie like J1ID, ve

  • Unicode Text Extract

    It looks this problem is not uncommon... I have a PostScript file that is generated by a 3rd party product. Distiller converts it to PDF, but I cannot search or copy a text. It looks this is because the ToUnicode CMap information is not readily avail

  • Embed PDF into Excel

    I realize that this is a combination of an adobe question and an excel question, but the forums that have attempted to answer this question for others don't solve my problem.  The adobe instructions for inserting a pdf into an excel cell say:   "To e