Abstract Class:-Real Time Example

前端 未结 5 1855
遥遥无期
遥遥无期 2020-12-14 16:27

Recently in a interview I was asked a very general question \"what is abstract in java\".I gave the definition and it was followed with some other question on abstract as wh

相关标签:
5条回答
  • 2020-12-14 16:56

    You should be able to cite at least one from the JDK itself. Look in the java.util.collections package. There are several abstract classes. You should fully understand interface, abstract, and concrete for Map and why Joshua Bloch wrote it that way.

    0 讨论(0)
  • 2020-12-14 17:01

    Here, Something about abstract class...

    1. Abstract class is an incomplete class so we can't instantiate it.
    2. If methods are abstract, class must be abstract.
    3. In abstract class, we use abstract and concrete method both.
    4. It is illegal to define a class abstract and final both.

    Real time example--

    If you want to make a new car(WagonX) in which all the another car's properties are included like color,size, engine etc.and you want to add some another features like model,baseEngine in your car.Then simply you create a abstract class WagonX where you use all the predefined functionality as abstract and another functionalities are concrete, which is is defined by you.
    Another sub class which extend the abstract class WagonX,By default it also access the abstract methods which is instantiated in abstract class.SubClasses also access the concrete methods by creating the subclass's object.
    For reusability the code, the developers use abstract class mostly.

    abstract class WagonX
    {
       public abstract void model();
       public abstract void color();
       public static void baseEngine()
        {
         // your logic here
        }
       public static void size()
       {
       // logic here
       }
    }
    class Car extends WagonX
    {
    public void model()
    {
    // logic here
    }
    public void color()
    {
    // logic here
    }
    }
    
    0 讨论(0)
  • 2020-12-14 17:07

    The best example of an abstract class is GenericServlet. GenericServlet is the parent class of HttpServlet. It is an abstract class.

    When inheriting 'GenericServlet' in a custom servlet class, the service() method must be overridden.

    0 讨论(0)
  • 2020-12-14 17:09

    A good example of real time found from here:-

    A concrete example of an abstract class would be a class called Animal. You see many animals in real life, but there are only kinds of animals. That is, you never look at something purple and furry and say "that is an animal and there is no more specific way of defining it". Instead, you see a dog or a cat or a pig... all animals. The point is, that you can never see an animal walking around that isn't more specifically something else (duck, pig, etc.). The Animal is the abstract class and Duck/Pig/Cat are all classes that derive from that base class. Animals might provide a function called "Age" that adds 1 year of life to the animals. It might also provide an abstract method called "IsDead" that, when called, will tell you if the animal has died. Since IsDead is abstract, each animal must implement it. So, a Cat might decide it is dead after it reaches 14 years of age, but a Duck might decide it dies after 5 years of age. The abstract class Animal provides the Age function to all classes that derive from it, but each of those classes has to implement IsDead on their own.

    A business example:

    I have a persistance engine that will work against any data sourcer (XML, ASCII (delimited and fixed-length), various JDBC sources (Oracle, SQL, ODBC, etc.) I created a base, abstract class to provide common functionality in this persistance, but instantiate the appropriate "Port" (subclass) when persisting my objects. (This makes development of new "Ports" much easier, since most of the work is done in the superclasses; especially the various JDBC ones; since I not only do persistance but other things [like table generation], I have to provide the various differences for each database.) The best business examples of Interfaces are the Collections. I can work with a java.util.List without caring how it is implemented; having the List as an abstract class does not make sense because there are fundamental differences in how anArrayList works as opposed to a LinkedList. Likewise, Map and Set. And if I am just working with a group of objects and don't care if it's a List, Map, or Set, I can just use the Collection interface.

    0 讨论(0)
  • 2020-12-14 17:09

    I use often abstract classes in conjuction with Template method pattern.
    In main abstract class I wrote the skeleton of main algorithm and make abstract methods as hooks where suclasses can make a specific implementation; I used often when writing data parser (or processor) that need to read data from one different place (file, database or some other sources), have similar processing step (maybe small differences) and different output.
    This pattern looks like Strategy pattern but it give you less granularity and can degradated to a difficult mantainable code if main code grow too much or too exceptions from main flow are required (this considerations came from my experience).
    Just a small example:

    abstract class MainProcess {
      public static class Metrics {
        int skipped;
        int processed;
        int stored;
        int error;
      }
      private Metrics metrics;
      protected abstract Iterator<Item> readObjectsFromSource();
      protected abstract boolean storeItem(Item item);
      protected Item processItem(Item item) {
        /* do something on item and return it to store, or null to skip */
        return item;
      }
      public Metrics getMetrics() {
        return metrics;
      }
      /* Main method */
      final public void process() {
        this.metrics = new Metrics();
        Iterator<Item> items = readObjectsFromSource();
        for(Item item : items) {
          metrics.processed++;
          item = processItem(item);
          if(null != item) {
    
            if(storeItem(item))
              metrics.stored++;
            else
              metrics.error++;
          }
          else {
            metrics.skipped++;
          }
        }
      } 
    }
    
    class ProcessFromDatabase extends MainProcess {
      ProcessFromDatabase(String query) {
        this.query = query;
      }
      protected Iterator<Item> readObjectsFromSource() {
        return sessionFactory.getCurrentSession().query(query).list();
      }
      protected boolean storeItem(Item item) {
        return sessionFactory.getCurrentSession().saveOrUpdate(item);
      }
    }
    

    Here another example.

    0 讨论(0)
提交回复
热议问题