Java静态方法和非静态方法

来自CloudWiki
跳转至: 导航搜索

静态方法和非静态方法

本节中使用static修饰的方法,表示静态方法,无需定义对象,可以通过类名直接使用。格式如下:

[数据类型 接收变量名=]类名.方法名([实参1,实参2,……]);

Java类的成员方法中我们学习的方法 是非静态方法,必须建立对象才能使用。

【实例3-3】计算立方体的体积程序设计。

public class Box {
//声明方法
public int calVolume1 (int width,int height,int depth) { 
	return (width * height * depth);
}
//声明方法
public static int calVolume2 (int width,int height,int depth) { 
	return (width * height * depth);
}
}
public class Main {
public static void main(String[] args){
	Box b1=new Box ();
	int volume=b1.calVolume1(10,20,50);//使用对象.方法名调用
	int volume1=calVolume2(10,20,50);//使用类名.方法名调用
}
}

程序int volume=b1.calVolume1(10,20,50);表示由对象b1调用了方法calVolume1并传入了10,20,50三个实际参数。