Java object-oriented (five) abstract

I. Overview of the abstract

  1, derived from

    The method of the parent class is rewritten its subclasses have subclasses respective different implementations. Then the parent class method declaration and method body, meaning there is only a statement, but there is no method body of meaning.

    We have no way subject method is called abstract methods . Java syntax requirements includes abstract methods of the class is an abstract class .

  2, the definition of

    •    Abstract method : There is no method body approach.
    •    Abstract class : abstract class contains methods.

Two, abstract using the format

  1, abstract methods

    Use the keyword abstract modification method, which has become abstract methods, abstract methods contain only a method name, and no method body.

   Definition Format:

Modifier abstract return type method name (parameter list);

  2, abstract class

    If a class contains abstract methods, the class must be abstract class.

   Definition Format:

abstract class name of the class { 
   // method body   
}

  3, abstract use

    Subclass inherits the abstract class of all parent class abstract method must be rewritten . Otherwise, the subclass must also be declared abstract.

   Ultimately, there must be a subclass implementation of the abstract methods of the parent class, otherwise, you can not create an object from the initial to the final of the parent class subclass meaningless.

   Demo:

. 1  public  class Cat the extends Animal {
 2    public  void RUN () {
 . 3      System.out.println ( "~ cat walking on the wall" );
 . 4    }
 . 5  } 
 . 6  public  class CatTest {
 . 7    public  static  void main (String [ ] args) {
 . 8      // create a subclass object 
. 9      Cat = C new new Cat ();
 10      // calls the run method 
. 11      c.run ();
 12 is    }
 13 is  } 
 14  output:
 15 kittens walking on the wall ~~~

 

    Note : At this point the overridden method, is a subclass of complete realization of the abstract methods of the parent class, we will rewrite this method of operation, also called realization .

Third, pay attention

  1, abstract class can not create objects , if created, but an error by the compiler can not only create objects in its non-abstract subclasses.

  2, abstract class can have constructor for a subclass is to create objects, initialize the parent class members to use.

  3, an abstract class, an abstract method can not necessarily, but there must be a class abstract methods abstract class.

  4, a subclass of abstract class must override the abstract parent class all the abstract methods , otherwise, an error by the compiler and can not, unless the subclass is also abstract class.

 

Guess you like

Origin www.cnblogs.com/niujifei/p/11368744.html