懂JAVA的过来帮个忙啊?小弟先谢谢了

来源:百度知道 编辑:UC知道 时间:2024/06/06 14:34:21
interface Shape{
double area();
}

class Circle implements Shape{ //圆类实现接口
private double radius;
public Circle(double radius){
this.radius=radius;
}
public void setRadius(double radius){
this.radius=radius;
}
public double getRadius(){
return radius;
}
public double area(){ //实现接口中的方法
return Math.PI*radius*radius;
}
}
class Rectangle implements Shape{ //矩形类实现接口Shape
private double length,width;
public Rectangle(double length,double width){
this.length=length;
this.width=width;
}
public void setLW(double length,double width){
this.length=length;
this.width=width;
}
public double getLength(){
return length;
}
public double getWidth(){
return width;
}
public double area(){ //实现接口中的方法
return length*width;
}
}

1.帮我写个主方法 让它能输出圆和长方形的面积。
2.帮忙解释下那么多的 th

1:
public static main(String[] args)
{
Shape circle=new Circle(50);
Shape rectangle=new Rectangle(20,20);
System.out.println("Area of circle is:"+circle.area());
System.out.println("Area of rectangle is:"+rectangle.area());
}

2:
public void setRadius(double radius){

//右边的radius是上面的参数radius
//左边的this.radius是Circle类的私有数据radius
//这个语句就是把参数radius的值赋给Circle的私有数据radius
this.radius=radius;
}

3:
接口其实就跟家里电器用的插头差不多.电脑、冰箱、洗衣机都是三脚插头,都是相同的接口,就可以插到同一个插座上。Circle和Rectangle都是形状,凡是形状都可以得到面积,因此Circle和Rectangle都可以得到面积。

4:
set和get是用来操作私有数据的,面向对象编程强调封装,尽量不应该直接操作私有数据,而应该通过set和get方法.