Java面向对象编程错误

不知道代码应该放在那里

一个空类的代码如下所示,public 是类的访问修饰符号(目前可以忽略),class 是定义类的关键字,Rectangle是类的名字,接下来的{ } 中包含类的成员(目前没有任何成员):

public class Rectangle {
	
}

现在我们来给他添加一个成员,表示长方形的宽度,宽度是数值,因此我们选择了int作为类型,width作为属性的名字。代码就编程这样了。

public class Rectangle {
	int width;	
}

我们在为长方形的类型添加一个属性,表示长方形的长度。 int length 代码就编程这样了

public class Rectangle {
	int width;
	int height;
}

然后我们在为Rectangle类添加一个功能,计算自己的面积。功能使用方法来定义。因为是计算面积,我们就定义方法名为area,在方法中打印输出面积。代码就编程这样了。

public class Rectangle {
	int width;
	int height;
	public void getArea(){
		System.out.println("面积为"+width * height);
	}
}

这样一个类就定义好了,怎么使用这个类来创建具体的一个长方形对象,然后利用其中的方法,输出面积呢?

public class Rectangle {
	int width;
	int height;
	public void getArea(){
		System.out.println("面积为"+width * height);
	}
	//在主函数使用类创建对象,调用对象,设置属性,调用方法
	public static void main(String[] args) {
		Rectangle rect = new Rectangle();  // 创建对象
		rect.height = 100;  // 设置对象的属性值
		rect.width = 90;
		rect.getArea(); // 调用对象的方法
	}	
}

典型的错误

在主函数中定义成员属性和方法
如下所示,在main函数中定义了,类的属性和方法,这是错误的。方法中不能定义方法,类的成员都要直接写在类的{ } 里面。不能写在方法的里面。

public class Rectangle {
	public static void main(String[] args) {
		int width;
		int height;
		public void getArea(){
			System.out.println("面积为"+width * height);
		}
	}	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值