首页 > 其他 > 详细

第四周课程总结&试验报告(二)

时间:2019-09-19 18:12:35      阅读:83      评论:0      收藏:0      [点我收藏+]

实验二 Java简单类与对象

实验目的

掌握类的定义,熟悉属性、构造函数、方法的作用,掌握用类作为类型声明变量和方法返回值;

理解类和对象的区别,掌握构造函数的使用,熟悉通过对象名引用实例的方法和属性;

理解static修饰付对类、类成员变量及类方法的影响。

第四周总结:

一::String类

1:实例化String对象,String可以采取直接赋值的方式进行操作;

2:“”==“”可以用来进行内容的比较,但是单纯写‘==’不会只进行内容上的比较,还有地址的比较;

3:equals()方法可以只进行内容上的比较;

4:String还可以使用new关键字来实例化;

5:String类常用操作方法 (p110);

6:字符串可以使用toCharrArray()方法变成一个字符数组;

7:String可以使用indexOf()方法返回指定的字符串位置。

二:包的使用:

1:package是在使用多个类或接口时,为了避免名称重复而采用的一种措施,直接在程序中加入package关键字即可。

2:如果几个类存放不同包中,在使用类的时候必须通过import语句进行导入;

3:系统常用包(p239);

实验内容

写一个名为Rectangle的类表示矩形。其属性包括宽width、高height和颜色color,width和height都是double型的,而color则是String类型的。要求该类具有:

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

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

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

实验代码:

class test {
    private double width;
    private double height;
    private String color;

    public test() {
    }

    public test(double width, double height, String color) {
        this.setWidth(width);
        this.setHeight(height);
        this.setColor(color);
    }

    public void setWidth(double w) {
        width = w;
    }

    public void setHeight(double h) {
        height = h;
    }

    public void setColor(String c) {
        color = c;
    }

    public double getWidth() {
        return width;
    }

    public double getHeight() {
        return height;
    }

    public String getColor() {
        return color;
    }

    public double getArea() {
        return width * height;
    }

    public double getLength() {
        return 2 * (width + height);
    }

}

public class Rectangle {
    public static void main(String[] args) {
        test t = null;
        t = new test(15, 18, "blue");
        System.out.println("周长为"+t.getLength());
        System.out.println("面积为"+t.getArea());
    }
}

技术分享图片

第四周课程总结&试验报告(二)

原文:https://www.cnblogs.com/hhl296738954/p/11551470.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!