为了账号安全,请及时绑定邮箱和手机立即绑定

java函数加不加static有何不同?

java函数加不加static有何不同?

JVM
开满天机 2018-11-26 13:09:40
publicclassA{publicstaticinttestMethod(){return1;}}与publicclassA{publicinttestMethod(){return1;}}假设我现在要调用方法testMethod.publicclassB{publicvoidmain(String[]args)...
查看完整描述

1 回答

?
海绵宝宝撒

TA贡献1809条经验 获得超8个赞

java中声明为static的方法称为静态方法或类方法。静态方法可以直接调用静态方法,访问静态变量,但是不能直接访问实例变量和实例方法。静态方法中不能使用this关键字,因为静态方法不属于任何一个实例。静态方法不能被子类的静态方法覆盖。
例如:
static class CompanyEmployee{
public static string GetCompanyName(string name) { ... }
public static string GetCompanyAddress(string address) { ... }
}
一般来说,类中标注了static的函数能在类外直接引用,比如说:
String M_string1 =CompanyEmployee.GetCompanyName(M_string2)
而没有标注static的函数则必须声明一个类的实体,有实体来引用。比如说:
static class CompanyEmployee{
public string GetCompanyName(string name) { ... } //没有Staticpublic static string GetCompanyAddress(string address) { ... }
}
CompanyEmployee M_CompE = new CompanyEmployee();
String M_string1 =M_CompE.GetCompanyName(M_string2);//静态类

查看完整回答
反对 回复 2018-12-12
  • 1 回答
  • 0 关注
  • 655 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信