The difference between abstract and general code

What is the difference between the word "abstract" and the "common" code in the case of Java? Are both the same?

+3
source share
4 answers

Abstract and generics are completely different things in the syntax and semantics of Java.

abstract is a keyword and indicates that the class does not contain a full implementation, therefore it cannot be created.

Example:

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

MyClass contains a definition of the public public void myMethod () 'method, but does not specify an implementation - the implementation should be provided by a subclass, usually called a specific subclass, so an abstract class defines an interface, possibly with some implementation details.

, . , API Java.

, List<String> " String". List<Integer> - List, Integer.

API , .

+6

- , , .

Java abstract . , ( ) . 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.
   }
}

- , , , ; .

Generic Generics Java, , - . ArrayList, , , , ArrayList, ( ArrayList, ints). Generics Java, , ints ArrayList ( 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.
   }
}
+5

, :

  • ,

  • ,


, :

  • - , ,
  • , , , - -.

: Store storeValue getValue. , , . , storeValue getValue. .

:

  • -, / , "instanceof"
  • , !
  • , , .
  • , , - , , , ,
  • / Vanilla ( ), Generics .
  • - -, , .

:   "", String ( ) Number ,

+3
source

Annotation is used to determine what requires an additional definition of functionality before it is considered "complete" (or specific in Java-certification-test-terms). Generic means a class that can handle a wide variety of data types that you define when you instantiate the class.

+2
source

Source: https://habr.com/ru/post/1714176/


All Articles