JavaSE系列代码08:方法的重载

Overload may be familiar to us, which can be translated into overload. It means that we can define some methods with the same name, distinguish these methods by defining different input parameters, and then when calling again, VM will select appropriate methods to execute according to different parameter styles.

class Cylinder
{
  private double radius; 
  private int height; 
  private double pi=3.14;
  private String color;
  public double SetCylinder(double r, int h)    //重载方法
  { 
    radius=r;
    height=h;
    return r+h;
  }
  public void SetCylinder(String str)          //重载方法
  {
    color=str;
  }
  public void show()
  {
    System.out.println("圆柱的颜色为:"+color);
  }
  double area()
  {
    return pi* radius* radius;
  }
  double volume()
  {
    return area()*height; 
  }
}
public class Javase_08   //定义主类
{
  public static void main(String[] args)
  {
    double r_h;
    Cylinder volu=new Cylinder();
    r_h=volu.SetCylinder(2.5, 5);   //设置圆柱的底半径和高
    volu.SetCylinder("红色");      //设置圆柱的颜色
    System.out.println("圆柱底和高之和="+r_h);
    System.out.println("圆柱体体积="+volu.volume());
    volu.show();
  }
}
发布了13 篇原创文章 · 获赞 160 · 访问量 8541

猜你喜欢

转载自blog.csdn.net/blog_programb/article/details/105377038