1 package com.Shen;
2
3 public class Test2 {
4 public static void main(String args[]){
5 AreaRect rect1;//声明对象,用AreaRect 这个类来声明rect这个对象(变量),类是一种数据类型
6 rect1=new AreaRect();
7 /*new:为rect1这个对象分配变量(一种运算符)(将AreaRect这个类中变量创建出来并交由rect1控制),
8 到此rect1这个对象才产生,AreaRect()为类的构造方法,一个类可以创建多个对象
9 */
10 AreaRect rect2=new AreaRect();//声明对象同时并分配变量
11 rect1.height=10;//对象通过.这个运算符操作自己的变量和运算方法
12 rect1.width=12;
13 rect2.width=15;
14 rect2.height=20;
15 double area1=rect1.getArea();
16 double area2=rect2.getArea();
17 System.out.println("矩形1的面积:"+area1);
18 System.out.println("矩形2的面积:"+area2);
19 }
20 }
1 package com.Shen;
2
3 public class AreaRect {
4 //class AreaRect 为类声明,AreaRect为类名称,花括号中为类体内容,此类中无主方法,所以非主类
5 double width;
6 //变量声明,称为域变量/成员变量
7 double height;
8 double getArea(){
9 //对于getArea这个方法的定义,方法后面要加括号
10 double area=width*height;
11 return area;
12 }
13 }