Java 抽象类:-实时示例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18944539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:47:25  来源:igfitidea点击:

Abstract Class:-Real Time Example

javaclassabstract-class

提问by TheGraduateGuy

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 what is abstract method and difference between abstract method and concrete method and etc. Then at last interviewer asked to give a real time example when I should use or define a class as abstract.I got confused.I gave some example but he was not convinced.

最近在一次采访中,我被问到一个非常笼统的问题“java 中的抽象是什么”。我给出了定义,然后是其他一些关于抽象的问题,如什么是抽象方法以及抽象方法与具体方法之间的区别等等。然后最后面试官要求举一个实时的例子,我应该在什么时候使用或定义一个类为抽象的。我很困惑。我举了一些例子,但他不相信。

I googled it but found no real solution.

我用谷歌搜索但没有找到真正的解决方案。

So can someone give me real time example i.e. when he defined a class as abstract in his/her project and why?

那么有人可以给我实时示例,即当他在他/她的项目中将一个类定义为抽象类时,为什么?

Thanks.

谢谢。

采纳答案by Rahul Tripathi

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.

抽象类的一个具体示例是名为 Animal 的类。你在现实生活中看到很多动物,但动物只有种类。也就是说,你永远不会看到紫色和毛茸茸的东西,然后说“那是一种动物,没有更具体的定义方法”。相反,你会看到一只狗、一只猫或一头猪……所有的动物。关键是,你永远看不到走动的动物,而不是更具体的其他东西(鸭子、猪等)。Animal 是抽象类,Duck/Pig/Cat 都是从该基类派生的类。动物可能会提供一个称为“年龄”的函数,为动物增加 1 年的生命。它还可能提供一个名为“IsDead”的抽象方法,当调用该方法时,它会告诉您动物是否已经死亡。由于 IsDead 是抽象的,每只动物都必须执行它。因此,猫可能会在 14 岁后决定它死了,但鸭子可能会在 5 岁后决定它死。抽象类 Animal 为所有派生自它的类提供 Age 函数,但这些类中的每一个都必须自己实现 IsDead。

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.

将 List 作为抽象类是没有意义的,因为 anArrayList 与 LinkedList 的工作方式存在根本差异。同样,映射和设置。如果我只是处理一组对象而不关心它是 List、Map 还是 Set,我可以只使用 Collection 接口。

回答by duffymo

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

您应该能够从 JDK 本身中至少引用一个。看java.util.collections包里。有几个抽象类。你应该完全理解接口、抽象和具体,Map以及为什么 Joshua Bloch 这样写。

回答by Luca Basso Ricci

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 patternbut 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);
  }
}

Hereanother example.

这里再举一个例子。

回答by vikas agrahari

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.
  1. 抽象类是一个不完整的类,所以我们不能实例化它。
  2. 如果方法是抽象的,则类必须是抽象的。
  3. 在抽象类中,我们同时使用抽象和具体方法。
  4. 同时定义抽象类和最终类是非法的。

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.

如果您想制造一辆新车(WagonX),其中包含另一辆车的所有属性,如颜色、尺寸、引擎等。并且您想在您的汽车中添加一些其他功能,如模型、baseEngine。那么您只需创建一个抽象在类 WagonX 中,您将所有预定义的功能用作抽象,而另一个功能是具体的,由您定义。
另一个扩展抽象类WagonX的子类,默认情况下它还访问抽象类中实例化的抽象方法。子类还通过创建子类的对象来访问具体方法。
为了代码的可重用性,开发人员主要使用抽象类。

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
}
}

回答by user3187491

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

抽象类的最佳示例是GenericServlet. GenericServlet是 的父类HttpServlet。它是一个抽象类。

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

在自定义 servlet 类中继承“GenericServlet”时,service()必须覆盖该方法。