对象类的构造器编写

构造器函数编写

我们在使用一个类的时候其实就是在使用他的实例,每一个类对象都可以构造很多个实例。那么我们要如何来编写呢,我们来用一个示例代码做演示:
使用编辑工具Eclipse
我们首先建立一个Java文件起名为Shapes.java,其代码如下:

public class Shapes {
	private int width = 350;
	private int height = 350;

	public int getWidth() {
		return width;
	}
	public void setWidth(int w) {
		width = w;
	}
	public int getHeight() {
		return height;
	}
	public void setHeight(int h) {
		height = h;
	}
	public Shapes() {

	}
	public Shapes(int w, int h) {
		width = w;
		height = h;
	}
	public int getArea() {
		return width * height;
	}
	public int getGirth() {
		return (width + height) * 2;
	}
}

针对我们建立的这个类对象,我们设置了两个int类型的属性,并将他们设置为私有访问属性,就是只能有他自己本身可以访问,为了可以操作这两个属性,分别为他们建立了get和set方法。针对get和set方法将在以后的章节中介绍(在的ava中这是两个非常重要的获取和设置的格式)。
在他们下面我们创建了两个构造函数,**构造函数(构造器)**与其他方法最大的不同就是构造函数是不能有返回值的,因为他的主要作用就是创建对象实例,但是我们可以在创建对象实例的时候做其他更多的事情,通常我们最常用的是无参数构造函数,同时我们也可以建立有参数的构造函数。
另外我们还建立了两个方法,用来得到对象的面积和周长。
下面我们来建立测试文件,用来演示具体使用方法。
Demo.java的代码格式如下:

public class Demo {
	public static void main(String[] args) {
		Shapes shapes1=new Shapes();
		System.out.println("shapes1的width属性值为:" + shapes1.getWidth());
		System.out.println("shapes1的height属性值为:" + shapes1.getHeight());
		System.out.println("shapes1的面积为:" + shapes1.getArea());
		System.out.println("shapes1的周长为:" + shapes1.getGirth());
		shapes1.setWidth(200);
		shapes1.setHeight(200);
		System.out.println("shapes1修改后的width属性值为:" + shapes1.getWidth());
		System.out.println("shapes1修改后的height属性值为:" + shapes1.getHeight());
		System.out.println("shapes1修改后的面积为:" + shapes1.getArea());
		System.out.println("shapes1修改后的周长为:" + shapes1.getGirth());
		Shapes shapes2=new Shapes(150,150);
		System.out.println("shapes2的width属性值为:" + shapes1.getWidth());
		System.out.println("shapes2的height属性值为:" + shapes1.getHeight());
		System.out.println("shapes2的面积为:" + shapes1.getArea());
		System.out.println("shapes2的周长为:" + shapes1.getGirth());
	}
}

我们首先使用无参数的构造函数来创建了一个对象实例shapes1利用他打印出对象的属性和方法获得的返回值,并利用set方法修改对象的属性值。
之后我们又利用有参的构造函数来创建了对象实例shapes2。
大家可以看看他们之间的区别。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值