对象的使用

作业
定义一个矩形类Rectangle:(知识点:对象的创建和使用)
1、定义三个方法:getArea()求面积、getPer()求周长,showAll()分别在控制台输出长、宽、面积、周长;
2、有2个属性:长length、宽width;
3、创建一个Rectangle对象,并输出相关信息。
---------------------------------------------------------

public class Rectangle {
    // 类名Rectangle
    String name; // 属性 名字
    int length; // 属性 长度
    int width; // 属性 宽度

    public void showAll() {
        System.out.println(name + "的长为" + length);
        System.out.println(name + "的宽为" + width);
    } // 成员方法-长度、宽度

    public void getArea() {
        System.out.println(name + "的面积为" + (length * width));
    } // 成员方法-面积

    public void getPer() {
        System.out.println(name + "的周长为" + ((length + width) * 2));
    } // 成员方法-周长
}

---------------------------------------------------------------------

public class Re2 {
    public static void main(String[] args) {
        Rectangle p = new Rectangle(); // 创建对象

        p.name = "矩形"; // 为成员变量name赋值
        p.length = 9; // 为成员变量length赋值
        p.width = 3; // 为成员width变量赋值

        p.showAll(); // 使用成员方法showAll
        p.getArea(); // 使用成员方法getArea
        p.getPer(); // 使用成员方法getPer

    }
}

原文地址:https://www.cnblogs.com/Hackman/p/12724739.html