java实现继承的代码_纯作业代码——Java实现接口、继承

//该代码实现结果为如果设定的长和宽相等则实例化正方形(Square)的类,否则实例化矩形类。

interface rect{

public double area();

public void getWidth(double Width);

public void getHeight(double Height);

}

class Rectangle1 implements rect{

double _width,_height;

public void getWidth(double Width){

_width=Width;

}

public void getHeight(double Height){

_height=Height;

}

public double area(){

return(_width*_height);

}

}

class Square extends Rectangle1{

public double area(){

return(_width*_width);

}

}

public class test1{

//At here ,I use the super class to define rect1.

static Rectangle1 rect1;

//set the value of width and height,then judge the shape,and Print them

public static void SetValue(double width ,double height){

if(width==height) rect1=new Square();

else rect1=new Rectangle1();

rect1.getWidth(width);

System.out.println("The Width value is :"+width+".");

rect1.getHeight(height);

System.out.println("The Height value is :"+height+".");

if(width==height) System.out.println("The shape is Square!");

else System.out.println("The shape is Rectangle!");

}

//get the result,and print it

public static void CalcIt(){

System.out.println("The result is :"+rect1.area()+".");

}

public static void main(String args[]){

//set the width and height

SetValue(10,10);

CalcIt();

System.out.println('/n');

//set the width and height

SetValue(10,50);

CalcIt();

}

}

这是教材上的一道题。首先写了一个计算矩形的类,然后再让写一个正方形的类来继承矩形类。并且要求重写父类中的至少一个方法。

于是有了这段代码。

各位尽管点评。

ps:高等教育出版社的书,“不'错'~~~~(>_

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值