抽象和通用代码之间的区别

3 java generics abstract

在Java的情况下,"抽象"和"通用"代码之间的区别是什么?这两个意思是一样的吗?

bra*_*ter 6

抽象和泛型在Java语法和语义上是完全不同的东西.

abstract是一个关键字,表示一个类不包含完整的实现,因此无法实例化.

例:

abstract class MyClass {
  public abstract void myMethod();
}
Run Code Online (Sandbox Code Playgroud)

MyClass的包含一个方法定义"公共抽象无效myMethod的()",但不指定一实现 - 实现必须由一个子类来提供,通常被称为一个具体的子类,这样一个抽象类定义了一个接口,或许与一些实施详情.

泛型的使用表明可以参数化类的方面.我发现最容易理解的例子是Java Collections API.

例如,List<String>可以读作'String类型的对象列表'.List<Integer>是相同的List接口,但只接受Integer类型的对象.

在Collections API中,它为集合提供类型安全性,否则需要样板来检查类型并进行适当的转换.


小智 5

摘要 - 除了具体的现实,特定的对象或实际的实例之外.

在Java中,您可以在类和方法定义中找到单词abstract.它意味着该类无法实例化(我只能用作超类),或者必须由子类覆盖该方法.一个例子是Animal类,Animal太模糊不能创建一个实例,但是Animal共享应该在Animal类中定义的公共属性/功能.

public abstract class Animal{
   protected int calories;

   public void feed(int calories){
      weight += calories;
   }

   public abstract void move(); // All animals move, but all do not move the same way
                                // So, put the move implementation in the sub-class
}

public class Cow extends Animal{
    public void move(){
       // Some code to make the cow move ...
    }
}

public class Application{
   public static void main(String [] args){
      //Animal animal = new Animal()   <- this is not allowed
       Animal cow = new Cow() // This is ok.
   }
}
Run Code Online (Sandbox Code Playgroud)

通用 - 适用于或引用属,类,群组或种类的所有成员; 一般.

当明确声明某个容器对象中包含哪种类型的对象时,术语Generic或Generics在Java中使用.以ArrayList为例,我们可以将我们想要的任何对象放入ArrayList中,但是这很容易导致错误(你可能会意外地在你的ArrayList中填入一个填充了int的字符串).泛型是用Java创建的,因此我们可以明确地告诉编译器我们只需要在ArrayList中使用int(使用泛型,当您尝试将String放入整数ArrayList时,编译器会抛出错误).

public class Application{
   public static void main(String [] args){
      ArrayList noGenerics = new ArrayList();
      ArrayList<Integer> generics = new ArrayList<Integer>();

      nogenerics.add(1);
      nogenerics.add("Hello"); // not what we want, but no error is thrown.

      generics.add(1);
      generics.add("Hello"); // error thrown in this case

      int total;
      for(int num : nogenerics)  
          total += num;
      // We will get a run time error in the for loop when we come to the
      // String, this run time error is avoided with generics.
   }
}
Run Code Online (Sandbox Code Playgroud)