方法重载
方法的重载是指一个类中可以定义多个相同名字。但参数不同的方法。调用时,会根据不同的参数选择不同的方法
example: Test
public calss Test{
void main(int a, int b) {
System.out.printlnn(a>b ? a:b);
}
//void maxFloat(float a, floatb) {//这种写法就是对不同的数据类型调用不同的方法,但效果都相同
// System.out..prinntln(a>b ? a:b);
//}
void max(float a, floatb){//方法构成重载,方法名相同,参数数量相同,但参数类型不同
System.out..prinntln(a>b ? a:b);
}
}
example: TestCircle
class Point{
private double x;
private double y;
Point(double _x, double _y){
x = _x;
y = _y;
}
public void setX(double X){//设定X坐标,只需传入一个参数,然后将它的值赋给x即可
//返回值类型void
x = X;
}
public void setY(double Y){
y = Y;
}
public double returnX(){//1.先确定方法名,2.定义返回值类型,3.参数
return x;//不需要参数
}
public double returnY(){
return y;
}
}
class Circle{
private Point o;
private double radius;
Circle(double r) {
radius = r;
o = new Point(0.0,0.0);
}
Circle(Point p, double r){//注意这里的参数是Point p
radius = r;
o = p;//将p所指向的坐标传递给o
}
Circle(Point p){
o = p;
radius = 1;
}
public double returnR(){
return radius;
}
public Point returnO(){//注意这里的返回值类型为Point
return o;
}
public double area(){
return radius * radius * 3.14;
}
public void setO(double x, double y){
o.setX(x);//修改Circle圆心
o.setY(y);
}
public void setR(double r){
radius = r;
}
}
public class TestCircle{
public static void main(String args[]) {
Circle c1 = new Circle(new Point(5.0,6.0),2.0);//在注意这里要写成Circle c1 而不是c1
Circle c2 = new Circle(2.0);
System.out.println("c1:(" + c1.returnO().returnX() + "), radius:" + c1.returnR());
System.out.println("c1 area = " + c1.area() );
c1.setO(3,0);
c1.setR(5.0);
System.out.println("c1:(" + c1.returnO().returnX() + "), radius:" + c1.returnR());
System.out.println("c1 area = " + c1.area() );
}
}