java--Constructors

Source: Internet
Author: User

The origin of the Java constructor: The constructor is a special method that is automatically called when an object is created, in order to initialize it.

When objects are created, the system initializes the properties of the object by default, the value of the base type property is 0 (numeric type), False (Boolean type), and all reference types are set to NULL. The constructor can change this default initialization. The constructor is not a function.

                       Requirements: The name of the constructor should match the name of the class. Invoking the constructor is the responsibility of the compiler, so you must let the compiler know which method is being called. So Java takes a method named constructor with the same name as the class.

 public   Class   person { public   String name;  public  int      age; The system automatically assigns public void person () {}  //  custom constructor /span> public  person (String name, int   age) { this . Name =        Name     this . Age = age; } 
void Main (string[] args) {        //New Person ("Xiaoming", "n"); System.out.println (P.age); System.out.println (P.name); }}

 Packagecollection;//Insert a section of this usage Public classleaf{Private intI=0; Leaf (inti) { This. i=i;} Leaf Increment () {i++; return  This; }                voidprint () {System.out.println ("I=" +i); }         Public Static voidmain (String [] args) {Leaf x=NewLeaf (100);//This statement is i=100 after the sentence. X.increment (). Increment (). Increment (). print ();//result is 103}}

No parameter constructor:

1.0: If you provide other constructors with arguments in the class, the compiler does not provide a default parameterless constructor.

    class  Animal {          Animal (String name) {}          publicstaticvoid  Main (string[] args) {              new   Animal ();          }      

This code cannot be compiled by

2.0: If you do not provide any constructors in the class, the compiler provides a default parameterless constructor.

    class  Animal {          publicstaticvoid  main (string[] args) {               New   Animal ();          }      }  

This section of code can be

3.0: If you provide a constructor, you do not need to manually add super () to your constructor, the compiler will add by default.

    classAnimal {Animal () {System.out.println ("----Animal no parameter constructor-----"); }      }      classHorseextendsAnimal {Horse () {//super ();//This line of code is the same as none.SYSTEM.OUT.PRINTLN ("----Horse no parameter constructor-----"); } Horse (inta) {//super ();//This line of code is the same as none.SYSTEM.OUT.PRINTLN ("----horse with a parametric constructor-----"); }           Public Static voidMain (string[] args) {Horse a=NewHorse (); Horse b=NewHorse (3); }      } 
results:
    1. ----animal without a parametric constructor-----
    2. ----horse without a parametric constructor-----
    3. ----animal without a parametric constructor-----
    4. ----Horse with a parametric constructor-----

4.0: If the parent class does not provide a parameterless constructor, the subclass will error:

 class   Animal {Animal ( int   a) {System.out.      println ( "----animal has a parametric constructor-----"  class  Horse extends   Animal {Horse () {System.out.println (----Horse parameterless constructor-----" );  public  static  void   main (string[] args) {Horse a  = new    Horse (); }}  
This code cannot be passed

5. If the constructor adds this reference to other constructors for that class, or if super () is added to call the parent class constructor, this and super must be in the first row of the constructor, This references other constructors and the super () statement does not appear at the same time

  class            Animal {Animal () {System.out.println ( "----Animal no parameter constructor-----"  class  Horse extends           Span style= "COLOR: #000000" > Animal {String name;              Horse () {System.out.println (----Horse no parameter constructor-----" this  ("Horse"); //  hint error,  } Horse (String name) { this<          /span>.name =   name; }}  

6. If the constructor adds this to other constructors that refer to the class, or if super () is added to call the parent class constructor, only static methods and static variables or constants if there are parameters in this and super

    classAnimal {Animal () {System.out.println ("----Animal no parameter constructor-----"); }      }      classHorseextendsAnimal {String name; Horse () { This(Getrondomname ()); <span style= "font-family:arial, Helvetica, Sans-serif;" >//Code Snippet a</span>SYSTEM.OUT.PRINTLN ("----Horse no parameter constructor-----"); } Horse (String name) {System.out.println ("----horse with a parametric constructor-----");//Code Snippet B             This. Name =name; }          StaticString Getrondomname () {intx = (int) (Math.random () * 5); String name=NewString[] {"Horse", "pig", "ox", "sheep", "cat"}[x]; returnname; }           Public Static voidMain (string[] args) {Horse a=New Horse (); }      } 

results:
    1. ----animal without a parametric constructor-----
    2. ----Horse with a parametric constructor-----
    3. ----horse without a parametric constructor-----

Reference Reference: http://www.jb51.net/article/75880.htm

Reference reference: http://blog.csdn.net/yoamy/article/details/51250218

java--Constructors

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.