类中的方法也可分为实例方法和类方法。在方法前面加上static就成了类方法,例如:
public class Example { float a, b; void sum(float x, float y) // 实例方法 { a = max(x, y); b = min(x, y); } static float getMaxSqrt(float x, float y) // 类方法 { float c; c = max(x, y) * max(x, y); return c; } static float max(float x, float y) // 类方法 { return x
- public class Example {
- float a, b;
- void sum(float x, float y)
- // 实例方法
- {
- a = max(x, y);
- b = min(x, y);
- }
- static float getMaxSqrt(float x, float y) // 类方法
- {
- float c;
- c = max(x, y) * max(x, y);
- return c;
- }
- static float max(float x, float y) // 类方法
- {
- return x
- }
- float min(float x, float y)
- // 实例方法
- {
- return x
- }
- }
- public class Example {
- float a, b;
- void sum(float x, float y)
- // 实例方法
- {
- a = max(x, y);
- b = min(x, y);
- }
- static float getMaxSqrt(float x, float y) // 类方法
- {
- float c;
- c = max(x, y) * max(x, y);
- return c;
- }
- static float max(float x, float y) // 类方法
- {
- return x
- }
- float min(float x, float y)
- // 实例方法
- {
- return x
- }
- }
一个类中的方法可以互相调用。但要注意:实例方法可以调用该类中的其他方法,例如,sum()可以调用max()和min()。类方法只能调用其他类方法,不能调用实例方法。例如,getMaxSqrt()只能调用max()而不能调用min()。
当类文件加载到内存时,实例方法不会被分配内存空间,只有在对象创建之后才会分配。而类方法在该类被加载到内存时就分配了相应的内存空间。
实例方法既能对类变量操作也能对实例变量操作。
类方法只能访问其他static方法。
类方法只能访问其他static数据,例如,类变量。