您的位置:首页 > 其它

关于构造函数的一些基本知识

2010-05-05 22:06 363 查看
package bisic;
/*
* 构造函数:
* 1.构建一个新的对象时使用的方法
* 2.和类名完全一致,不能有返回值类型
* 3.当没有指定构造函数时,编译器为类自动添加 形如 类名(){}的构造函数,一旦指定后编译器就不为你添加了
* 4.注意没有返回值类型,否则的话完全是另一个方法
*/
public class ConstructionRule {

public static void main(String[] args) {
Person1 tom = new Person1(1,25);//1.
System.out.println(tom.id);
System.out.println(tom.age);
//Person1 jerry = new Person1();//3.构造函数指定后编译器就不为你添加了形如 类名(){}的构造函数, 所以这句报错
Point p = new Point();
System.out.println(p.x);
System.out.println(p.y);
}

}

class Person1 {
int id;
int age = 20;

Person1(int id, int age) {//2.
this.id = id;
this.age = age;
}

}
/*
Person1(int _id, int _age) {
id = _id;
age = _age;
}
构造方法的另一种写法
*/

class Point {
//Point() {} //3.当没有指定构造函数时,编译器为类自动添加 形如 类名(){}的构造函数,所以这句写不写无所谓
int x;
int y;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: