views:

255

answers:

4

Hi,

What's the difference between the word "Abstract" and "Generic" code in case of Java? Are both mean the same?

+5  A: 

Abstract and Generics are completely different things in Java syntax and semantics.

abstract is a keyword, and indicates that a class does not contain a complete implementation, so cannot be instantiated.

Example:

abstract class MyClass {
  public abstract void myMethod();
}

MyClass contains a method definition 'public abstract void myMethod()', but does not specify an implementation - an implementation must be provided by a subclass, usually referred to as a concrete subclass, so an abstract class defines an interface, perhaps with some implementation detail.

The use of generics indicates that aspects of a class can be parameterized. I find the easiest to understand example is in the Java Collections API.

For example List<String> can be read as 'List of objects of type String'. List<Integer> is the same List interface, but only accepts objects of type Integer.

In the Collections API, it provides type-safety for collections that otherwise that otherwise require boilerplate to check types and cast appropriately.

Brabster
The example code will result in compile error. At least one member of an abstract class must be abstract, I guess.
Mohammad Alinia
Thanks @Mohammed Alinia, fixed the error.
Brabster
+2  A: 

Abstract is used to define something that requires additional definition of functionality before it is considered "complete" (or concrete in Java-certification-test-terms). Generic means it's a class that can handle a wide variety of data types that you define when you instantiate the class.

MattC
+4  A: 

Abstract - thought of apart from concrete realities, specific objects, or actual instances.

In Java you find the word abstract in class and method definitions. It implies that the class can not be instantiated (I can only be used as a super-class), or that a method must be overridden by a sub-class. A example of this is an Animal class, an Animal is too ambiguous to create an instance out of, however Animals share common attributes/functionality which should be defined in the Animal class.

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

Generic - of, applicable to, or referring to all the members of a genus, class, group, or kind; general.

The term Generic, or Generics, is used in Java when explicitly declaring what type of objects will be contained in some container object. Take an ArrayList for example, we can put any object we want into an ArrayList, but this can easily lead to bugs (You might accidentally put a String in your ArrayList that is filled with ints). Generics was created in Java so that we can explicitly tell the compiler that we only want ints in our ArrayList (with generics the compiler will throw an error when you try to put a String in to your integer 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.
   }
}
Michael
+2  A: 

Short, understandable answer:

  • Abstract code expresses an idea but not how to make it work

  • Generic code works with more than one kind of object, and knows what kind you gave it


Longer, but not wall-of-text:

Abstract specifies an interface, without the full implementation

  • Abstract classes have to be extended to be used, you can't create instances with a constructor
  • Abstract classes don't have to provide code for all methods -- they can give just the method name, return value(s), and checked exceptions thrown
  • This means you can use abstract methods when you want to allow something to work different ways.

Example: you can write an abstract Store class, with abstract storeValue and getValue methods. Then you extend it with different implementations for database storage, disk storage, networked storage, and memory storage. All use the same methods, except for the storeValue and getValue methods. You can use them interchangeably.

Generic code includes Type info, and may work with multiple types:

  • Generics don't really let you do anything you couldn't with vanilla Object inputs/outputs, and a lot of "instanceof" checks and object casting
  • They are easier to read, though!
  • Generic code specifies what kind of objects it works with, and lets you operate on groups of the same thing
  • Generic code lets you specify an algorithm without knowing what it's operating on -- when the algorithm is called, it can output the same type as the input, whatever the input might be
  • You don't have to cast to/from vanilla Objects (and check object type) if you use Generics to operate on different object types
  • The most common place for generics is operating on collections -- you can store a collection of something, without knowing what exactly it is
  • Generics can be fiendishly complicated

Example: you define an "add" method which adds String (or similar) objects end to end, or sums Number objects, or adds an element of one type to a Collection containing that type

BobMcGee