Package Com.mec.about_constructor;public class Point {private int row;private int col;private String name;public Final int Min_row = 1;public final int max_row = 25;public final int default_row = 1;public final int min_col = 1;public final int Max_col = 80;public final int default_col = 1;public String getName () {return name;} public void SetName (String name) {this.name = name;} Construction method (called only at new time) public point () {//Cannot write return value type, he does not return value type System.out.println ("The constructor is executed!") Setrow (100);//Because there is no way to determine the value in the relevant instantiation, so it is possible to kill his initial values Setcol (-20);} public void Setrow (int row) {if (Row < Min_row | | row > Max_row) {row = Default_row;} This.row = row;} public void Setcol (int col) {if (Col < Min_col | | col > max_col) {col = Default_col;} This.col = col;} public int GetRow () {return row;} public int Getcol () {return col;}}
Package Com.mec.about_constructor.demo;import Com.mec.about_constructor. Point;public class Demopoint {public static void main (string[] args) {Point pointone = new Point (); System.out.println (Pointone); System.out.println (Pointone.getrow () + "," + pointone.getcol () + "," + pointone.getname ());//If a class, whose members are of class type, Instead of the 8 basic type, the relevant member is Nullpointone.setrow (15) When the object//is instantiated, and no assignment is made; System.out.println (Pointone.getrow () + "," + Pointone.getcol ()); Point pointtwo = new Point (); System.out.println (Pointtwo.getrow () + "," + Pointtwo.getcol ());}}
Point pointone = new Point (), and at New Point (), the constructor of the point class is executed public point (), which creates an object of the point class.
To create a class that does not define a constructor, the Java compiler automatically adds a constructor with no arguments for the class
constructor Syntax Considerations :
1. Constructors can have modifiers, not write as default type
2. The constructor name must be the same as the name of the class
3. No return value, no void
4. Constructor parameters are optional and can have one or more parameters
call to constructor :
1. Call under a different package: apple al = new apple()
2. Subclasses call the constructor of the parent class: Super ();
How to instantiate an object : The name of the new constructor (parameter);
Java constructor vs. new keyword