【Java编程】方法的使用

来源:互联网 发布:宁波软件行业协会 编辑:程序博客网 时间:2024/05/22 05:07

方法:封装在一起来执行操作语句的集合,用来完成某个功能操作,在某些语言中称为函数或过程,特殊的方法main方法是程序执行的入口。

修饰符:决定了方法的工作范围,返回值类型必选,如果没有返回值,需写void。方法只能返回一个值。

方法的结构:

修饰符 返回值类型 方法名(){

方法体;

return 返回值;

}


方法的使用:引用对象.方法名(实参列表)(在同一个类方法之间的调用不需要引用类型)

ststic只能调用static方法,static方法调用无static的方法需要类调,new个对象

示例:调用static方法

public class Test{public static void cs() {System.out.println("我是static方法");}public static void main(String[] args) {// 调用static方法cs();}}


调用非static方法:需要new一个对象,通过对象来调

public class Test {public void cs() {System.out.println("我是非static方法");}public static void main(String[] args) {// 调用非static方法Test t = new Test();t.cs();}}


有返回值:

public class Test {public double cs(double d, double h) {// 求三角形的面积return d * h / 2;}public static void main(String[] args) {// 调用非static方法Test t = new Test();double area = t.cs(2, 4);System.out.println(area);}}




原创粉丝点击