鉴于学习过c语言,所以大多数内容就不一一记录。
public class ronth {
public static void main(String[] args) {
//通过对象调用普通方法
ronth tm = new ronth();
System.out.println(tm.math(10, 20, 30));
}
int math(int a,int b,int c){
int sum = a + b + c;
return sum;
}
}
public static void main(String[] args) {
//通过对象调用普通方法
ronth tm = new ronth();
System.out.println(tm.math(10, 20, 30));
}
int math(int a,int b,int c){
int sum = a + b + c;
return sum;
}
}
java方法类似于C语言的函数。
如上定义方法时,调用方法需要通过对象调用普通方法。
如上定义方法时,调用方法需要通过对象调用普通方法。
定义方法时 使用public static int math 则可以直接调用
public class ronth {
public static void main(String[] args) {
System.out.println(math(10, 20, 30));
}
public static int math(int a,int b,int c){
int sum = a + b + c;
return sum;
}
}
方法重载:
/** 求和的方法 */
public static int add(int n1, int n2) {
int sum = n1 + n2;
return sum;
}
// 方法名相同,参数个数不同,构成重载
public static int add(int n1, int n2, int n3) {
int sum = n1 + n2 + n3;
return sum;
}
// 方法名相同,参数类型不同,构成重载
public static double add(double n1, int n2) {
double sum = n1 + n2;
return sum;
}
// 方法名相同,参数顺序不同,构成重载
public static double add(int n1, double n2) {
double sum = n1 + n2;
return sum;
}
//编译错误:只有返回值不同,不构成方法的重载
public static double add(int n1, int n2) {
double sum = n1 + n2;
return sum;
}
//编译错误:只有参数名称不同,不构成方法的重载
public static int add(int n2, int n1) {
double sum = n1 + n2;
return sum;
}
}
public class ronth {
public static void main(String[] args) {
System.out.println(math(10, 20, 30));
}
public static int math(int a,int b,int c){
int sum = a + b + c;
return sum;
}
}
方法重载:
/** 求和的方法 */
public static int add(int n1, int n2) {
int sum = n1 + n2;
return sum;
}
// 方法名相同,参数个数不同,构成重载
public static int add(int n1, int n2, int n3) {
int sum = n1 + n2 + n3;
return sum;
}
// 方法名相同,参数类型不同,构成重载
public static double add(double n1, int n2) {
double sum = n1 + n2;
return sum;
}
// 方法名相同,参数顺序不同,构成重载
public static double add(int n1, double n2) {
double sum = n1 + n2;
return sum;
}
//编译错误:只有返回值不同,不构成方法的重载
public static double add(int n1, int n2) {
double sum = n1 + n2;
return sum;
}
//编译错误:只有参数名称不同,不构成方法的重载
public static int add(int n2, int n1) {
double sum = n1 + n2;
return sum;
}
}