方法就是一段可重复调用的代码段,也叫函数,用来供程序反复调用
一.方法的定义
定义一个方法,在主方法调用它:
public static void main(String[] args) {
// TODO Auto-generated method stub
fun();
fun();
fun();
System.out.println("hhhhhhhhh");
}
public static void fun(){
char c[] = {'q','w','e','r','t','y','u'};
for(int i = 0; i < c.length; i++){
System.out.print(c[i]);
}
System.out.println("");
}
程序运行结果为:
qwertyu
qwertyu
qwertyu
hhhhhhhhh
方法名第一个单词的首字母小写,之后每个单词的首字母大写,如printInt.
二.方法的重载
方法重载就是方法名相同,但参数的类型和参数的个数不同,通过参数类型的不同和参数个数的不同完成不同的功能。
public static void main(String[] args) {
// TODO Auto-generated method stub
int one = add(10,20);
int two = add(10,20,30);
float ttt = add(11.1f,22.3f);
System.out.println(one);
System.out.println(two);
System.out.println(ttt);
}
public static int add(int x, int y){
int z = 0;
z = x + y;
return z;
}
public static int add(int x, int y, int z){
int t = 0;
t = x + y + z;
return t;
}
public static float add(float x, float y){
float z = 0;
z = x + y;
return z;
}
程序运行结果为:
30
60
33.4
从程序中可以看到add方法被重载了三次,每次重载时参数个数或参数类型都不一样,调用时会根据参数个数和参数类型自动分类调用。
System.out.println()也属于重载方法,它可以打印任意类型的数据。
三.方法的重写
方法重写在父类与子类之间。当有时子类并不想原封不动地继承父类的方法,而是想作一定的修改时就要重写父类方法。子类中的方法与父类中的某一方法具有相同的方法名、返回类型和参数表,则新方法将覆盖原有的方法。
public class TestFrist extends Base{
public static void main(String[] args) {
// TODO Auto-generated method stub
Base b=new TestFrist();
b.test(0);
b.test((byte)0);
}
void test(int i)
{
i++;
System.out.println(i);
}
}
class Base
{
void test(int i)
{
System.out.print(i);
}
void test(byte b)
{
System.out.print(b);
}
}
程序运行结果为:
1
0