欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JAVA SE Method(方法)

程序员文章站 2022-06-21 14:46:23
...

1 丶方法的含义

方法是实现一个功能的函数模块.

通常情况下一个方法的组成如下:

访问修饰符    返回值类型    方法名(参数列表){

        方法体 ;

}

例子如下:

public void show(){
    System.out.println("java方法总结");//输出
}

 

2 丶方法的分类

根据函数是否带参数值或返回值有如下分类

 

  • 无参无返回值方法
  • 无参带返回值方法
  • 有参无返回值方法
  • 有参带返回值方法
//无参无返回值
public void show(){
    System.out.println("java方法总结");
}
//无参带返回值
public String show(){
    String str="无参带返回值";
    return str;
}
//有参无返回值
public void show(String _str){
    System.out.println(_str);
}
//有参带返回值
public String show(String _str){
    String str="这个是"+_str;
    return str;
}

3 丶方法的使用

需要调用方法时,先创建类的对象,再通过  对象名.方法名();

public Test{
	public static void main(String[] args) {
		Test test =new Test();//创建对象
		test.show();//调用方法
	}
	public void show(){
		System.out.println("调用show方法");
	}
}test.show();//调用方法
	}
	public void show(){
		System.out.println("调用show方法");
	}
}

4 丶方法的重载

重载即同一个类中,同一个方法的不同实现.  评断依据如下:

 

  • 方法名一致
  • 方法参数个数不同
  • 方法参数类型不同
  • 方法参数顺序不同
public Test{
	public static void main(String[] args) {
		Test test =new Test();
		test.show();
		test.show("包子");
		test.show("1","包子");
		test.show("包子","包子");
		test.show("包子","1");
	}
	public void show(){
		System.out.println("调用show方法");
	}
	public void show(String _str){
		System.out.println(_str);
	}
	public void show(String _str1,String _str2){
		System.out.println(_str1+_Str2);
	}
	public void show(String _str,int _num){
		System.out.println(_str+_num);
	}
	public void show(int _num,String _str){
		System.out.println(_str+_num);
	}
}

 

相关标签: 方法