实验二 Java简单类与对象

  • 实验目的
  • 掌握类的定义,熟悉属性、构造函数、方法的作用,掌握用类作为类型声明变量和方法返回值;
  • 理解类和对象的区别,掌握构造函数的使用,熟悉通过对象名引用实例的方法和属性;
  • 理解static修饰付对类、类成员变量及类方法的影响。
  • 实验内容
  1. 写一个名为Rectangle的类表示矩形。其属性包括宽width、高height和颜色color,width和height都是double型的,而color则是String类型的。要求该类具有:

(1) 使用构造函数完成各属性的初始赋值

(2) 使用get…()和set…()的形式完成属性的访问及修改

(3) 提供计算面积的getArea()方法和计算周长的getLength()方法、

实验代码:

public class Rectangle {
    private double width;
    private double height;
    private String color;
    public Rectangle(double width,double height,String color){
        this.width=width;
        this.height=height;
        this.color=color;
    }
    public double getWidth() {
        return width;
    }
    public void setWidth(double width) {
        this.width = width;
    }
    public double getHeight() {
        return height;
    }
    public void setHeight(double height) {
        this.height = height;
    }
    public String getColor() {
        return color;
    }
    public void setColor(String color) {
        this.color = color;
    }
    public double area(){
        double area=0;
        area=width*height;
        return area;
    }
    public double length(){
        double  length=0;
        length=(width+height)*2;
        return length;
    }
   
    public static void main (String[] args){
        Rectangle r1=new Rectangle(4.0,8.0,"red");
        Rectangle r2=new Rectangle(3.0,6.0,"green");
        if(r1.area()>r2.area()){
            System.out.println(r1.getHeight()+","+r1.getWidth());
        }
        else{System.out.println(r2.getHeight()+","+r2.getWidth());
       
        }
      System.out.println(r1.area());
      System.out.println(r2.area());
      System.out.println(r1.length());
        System.out.println(r2.length());
    }
}

运行截图:

 

 

2:银行的账户记录Account有账户的唯一性标识(11个长度的字符和数字的组合),用户的姓名,开户日期,账户密码(六位的数字,可以用0开头),当前的余额。银行规定新开一个账户时,银行方面提供一个标识符、账户初始密码123456,客户提供姓名,开户时客户可以直接存入一笔初始账户金额,不提供时初始余额为0。定义该类,并要求该类提供如下方法:存款、取款、变更密码、可以分别查询账户的标识、姓名、开户日期、当前余额等信息。

不会;get set 基本内容懂,操作起来一团糟

总结:

这周主要有关string类的学习,string类常用操作方法;

对象数组,了解了之后需要学习的(exception)异常;

包&对象数组;

还是有很多不足的地方,实验二的第一题到还能写出来,至于第二题对我来说就有点难度了,之后会在老师教的讲解中解决这一问题,亦或是询问同学