不知道代码应该放在那里
一个空类的代码如下所示,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);
}
}
}