Java实践(六)——构造方法与方法重载

实践目标

1.掌握类的构造方法的定义

2.掌握重载(重写)的概念

3.掌握构造方法的应用,对象的初始化

 

实践内容

1.不带参数的构造方法

2.带参数的构造方法

3.构造方法之间的引用

class Chap2_4_1 
{
	public static void main(String[] args) 
	{
		System.out.println("Hello World!");
		Point p1 = new Point(9);
		
		//不能直接引用  p1.Point();

		System.out.println("p1("+p1.x+","+p1.y+")");
	}
}
class Point
{
	//定义Point类的数据成员
	public int x,y;
	public static int number;//计数

	//定义构造函数(重载的概念)
	public Point(int x,int y){  //重写构造函数,带有参数
		this.x = x;
		this.y = y;
	}

	public Point()//重写默认构造函数,无参的。
	{
		this(0,0);
	}

	public Point(int x) //当我们只有x参数时,
	{
		this(x,0);
	}

	//当我们只有y参数时,能不能写成如下
	//public Point(int y)
	//{
	//	this(0,y);
	//}


	//定义Point类的方法成员
	public int getx(){
		return x;
	}
	public void setx(int x){
		this.x = x;
	}
	public int gety(){
		return y;
	}
	public void sety(int y){
		this.y = y;
	}

	//重写finalizer方法
	protected void finalize(){
		System.out.println("释放内存.");
	}
}


 

总结

 

posted @ 2012-09-26 11:20  涛涌四海  阅读(165)  评论(0编辑  收藏  举报