Chinaunix首页 | 论坛 | 博客
  • 博客访问: 6535785
  • 博文数量: 915
  • 博客积分: 17977
  • 博客等级: 上将
  • 技术积分: 8846
  • 用 户 组: 普通用户
  • 注册时间: 2005-08-26 09:59
个人简介

一个好老好老的老程序员了。

文章分类

全部博文(915)

文章存档

2022年(9)

2021年(13)

2020年(10)

2019年(40)

2018年(88)

2017年(130)

2015年(5)

2014年(12)

2013年(41)

2012年(36)

2011年(272)

2010年(1)

2009年(53)

2008年(65)

2007年(47)

2006年(81)

2005年(12)

分类: Java

2011-09-29 09:30:29

类中的方法也可分为实例方法和类方法。在方法前面加上static就成了类方法,例如:
  1. public class Example {     
  2.     float a, b;     
  3.     
  4.     void sum(float x, float y)     
  5.     // 实例方法      
  6.     {     
  7.         a = max(x, y);     
  8.         b = min(x, y);     
  9.     }     
  10.     
  11.     static float getMaxSqrt(float x, float y) // 类方法      
  12.     {     
  13.         float c;     
  14.         c = max(x, y) * max(x, y);     
  15.         return c;     
  16.     }     
  17.     
  18.     static float max(float x, float y) // 类方法      
  19.     {     
  20.         return x <= y ? y : x;     
  21.     }     
  22.     
  23.     float min(float x, float y)     
  24.     // 实例方法      
  25.     {     
  26.         return x <= y ? x : y;     
  27.     }     
  28. }    
  29. public class Example {  
  30.  float a, b;  
  31.   
  32.  void sum(float x, float y)  
  33.  // 实例方法   
  34.  {  
  35.   a = max(x, y);  
  36.   b = min(x, y);  
  37.  }  
  38.   
  39.  static float getMaxSqrt(float x, float y) // 类方法   
  40.  {  
  41.   float c;  
  42.   c = max(x, y) * max(x, y);  
  43.   return c;  
  44.  }  
  45.   
  46.  static float max(float x, float y) // 类方法   
  47.  {  
  48.   return x <= y ? y : x;  
  49.  }  
  50.   
  51.  float min(float x, float y)  
  52.  // 实例方法   
  53.  {  
  54.   return x <= y ? x : y;  
  55.  }  
  56. }  
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 <= y ? y : x; } float min(float x, float y) // 实例方法 { return x <= y ? x : y; } } 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 <= y ? y : x; } float min(float x, float y) // 实例方法 { return x <= y ? x : y; } }

一个类中的方法可以互相调用。但要注意:实例方法可以调用该类中的其他方法,例如,sum()可以调用max()和min()。类方法只能调用其他类方法,不能调用实例方法。例如,getMaxSqrt()只能调用max()而不能调用min()。

当类文件加载到内存时,实例方法不会被分配内存空间,只有在对象创建之后才会分配。而类方法在该类被加载到内存时就分配了相应的内存空间。

实例方法既能对类变量操作也能对实例变量操作。

类方法只能访问其他static方法。

类方法只能访问其他static数据,例如,类变量。

阅读(3315) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~