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;
}
//构造方法(仅仅在new的时候被调用)
public Point() {//不能写返回值类型,他根本就没有返回值类型
System.out.println("执行了构造方法!");
setRow(100);//因为在相关实例化的时候,没有办法确定里面的值,所以,这样可以定死他的初值
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());
//如果一个类,他的成员里面是类类型的,而不是8大基本类型的,则相关成员在对该对象
//进行实例化时,并且没有进行赋值时,他的初值为null
pointOne.setRow(15);
System.out.println(pointOne.getRow()
+ ", " + pointOne.getCol());
Point pointTwo = new Point();
System.out.println(pointTwo.getRow()
+ ", " + pointTwo.getCol());
}
}
Point pointOne = new Point();在new Point()时,执行Point类的构造方法public Point(),创建Point类的对象。
创建一个类可以不定义构造器,Java编译器会自动为这个类添加一个没有参数的构造器
构造器语法注意事项:
1.构造器可以有修饰符,不写即为default类型
2.构造器名称必须要和类的名称相同
3.不能有返回值,void也不行
4.构造器的参数可有可无,可以有一个也可以有多个参数
构造器的调用:
1.在不同的包下调用:apple al = new apple()
2.子类调用父类的构造器:super();
如何实例化一个对象:new 构造器名称(参数);