Java包练习:1、在src下新建包;2、在src下新建主类文件

1、在src下新建包: com.cn.p1,在该包中创建长方形的类,属性为私有属性长和宽,方法有构造方法,求面积,求周长方法

2、在src下新建主类文件,引入com.cn.p1包中的长方形类,创建长方形对象,输出面积周长

先给个目录结构图:

img


再贴两个类的代码:

package com.cn.p1;

public class Ract{
    private int width;
    private int height;
    public Ract(int width, int height){
        this.width = width;
        this.height = height;
    }

    public int getArea(){
        return this.width*this.height;
    }

    public int getRound(){
        return (this.width+this.height)*2;
    }
}

import com.cn.p1.Ract;

public class Main {
    public static void main(String[] args) {
        int width = 4;
        int height = 5;
        Ract ract = new Ract(width,height);
        int area = ract.getArea();
        int round = ract.getRound();
        System.out.println("面积:"+area+", 周长:"+ round);
    }
}