方法的定义
方法类似函数,可以执行某种功能。
命名规则:首字母小写,词语实行驼峰原则。
//加法
public class Demo{
public static void main(string[] args){
int sum = add(a:1,b:2);
System.out.println(sum);
}
public static int add(int a,int b){
//修饰符+返回值类型+方法名(参数类型 参数名)
return a+b;
}
}
方法的调用
Java中方法的调用主要分为以下三种:
一、静态方法
静态方法是指用static修饰的方法,静态方法的调用是通过类名来调用的,表现形式如下:
类名.方法名();
//调用静态方法
public class Students{
public static void main(String[] args){
Students.say();
}
public static void say(){
System.out.println("hello,student");
}
}
二、非静态方法
非静态方法是指没有用static修饰的方法,非静态方法的调用是通过对象来实现的,表现形式如下:
类名 对象名 = new 类名();
对象名.方法名();
//调用非静态方法
public class Students{
public static void main(String[] args){
Students student = new Students();
student.say();
}
public void say(){
System.out.println("hello,student");
}
}
三、方法之间的调用
方法与方法之间的调用,主要是在一个方法内部如何调用其他方法。
1静态方法调用其他方法
1)静态方法调用静态方法
在同类中,静态方法可以直接调用静态方法。
public class Students{
public static void main(String[] args){
say();
}
public static void say(){
System.out.println("hello,student");
}
}
在不同类中,可以使用:
类名.静态方法名();
public class Students{
public static void main(String[] args){
Teacher.say();
}
}
class Teacher{
public static void say(){
System.out.println("hello,student");
}
}
2)静态方法调用非静态方法
静态方法调用非静态方法,都必须通过对象来调用。
在同一类中调用:
public class Students{
public static void main(String[] args){
Students student = new Students();
student.say();
}
public void say(){
System.out.println("hello,student");
}
}
在不同类中调用
public class Students{
public static void main(String[] args){
Teacher student = new Teacher();
/*类名 对象名=new 类名()
创建对象时,类名为方法所在的类*/
student.say();
}
}
class Teacher{
public void say(){
System.out.println("hello,student");
}
}
2 非静态方法调用其他方法
1)非静态方法在同一类内调用其他方法
在同一类中,非静态方法可以直接调用静态方法和非静态方法。
public class Students{
public static void main(String[] args){
Students put = new Students();
put.output();
}
public void say(){
System.out.println("hello,student");
}
public static void song(){
System.out.println("hello,teacher");
}
public void output(){
say();
song();
}
}
2)非静态方法在不同类之间调用其他方法
public class Students{
public static void main(String[] args){
Students student = new Students();
student.output();
}
public void output(){
Teacher.say();
Teacher put = new Teacher();
put.song();
}
}
class Teacher{
public static void say(){
System.out.println("hello,student");
}
public void song(){
System.out.println("hello,teacher");
}
}
总的来说:
静态方法可以直接被调用,
同类中调用格式为:
静态方法名();
不同类中调用格式为:
类名.静态方法名();
非静态方法需要创建对象,才可以被调用,调用格式为:
方法所在的类名 对象名 = new 方法所在的类名() ;
对象名.方法名();
返回值的设置
-
如果方法返回值为一个数值,方法调用被当做一个值,int larger = max(30,40);
-
如果方法返回值为void,方法调用为一条语句,System.out.println(“num1==num2”)。
参考链接:
https://www.imooc.com/article/13423.
https://blog.csdn.net/plus_left/article/details/83663041