构造方法

题意:

/*
* 创建Rect 矩形类,有private修饰的length 和width两个成员变量,定义两个构造方法,一个无参数
* 用来对width和length赋值为0,另一个构造方法有两个参数分别用来对width和length赋值
* 再定义获得矩形面积的方法
* 在另一个类Test的 程序入口public static void main创建矩形的对象,创建矩形两个对象,
* 一个无参数一个有两个参数的对象,最后输出这两个矩形的面积
*/

package practic;
class Rect {
private int length;
    private int width;
    public Rect()//定义第一个无参数的构造方法
    {
        length=0;//对length赋值为0
        width=0;
    }
    public Rect (int length,int width)//创造第二个有参数的构造方法
    {
        this.length=length;
        this.width=width;
    }
    public int S()//定义获得矩形的面积的方法
    {
        return length*width;
    }
    public static void main(String[] args) {
        // TODO 自动生成的方法存根
    Rect rect=new Rect();//创建无参数对象
    Rect r=new Rect(5,6);//创造有参数对象
    int s1=rect.S();
    int s2=r.S();
    System.out.println(s1);
    System.out.println(s2);
    }
}

 

posted @ 2020-04-21 10:48  今天喝奶茶了吗  阅读(202)  评论(0)    收藏  举报