static 静态方法

程序员成长之旅 · 程序员成长之旅/Java学习/笔记 · 463 字

一句话总结就是 static 就是方便没有创建对象的时候执行方法

看两个文件体现

//StaticTest.java public class StaticTest{ public void testNo(){ System.out.println("没有Static测试成功"); } public static void testYes(){ System.out.println("有Static测试成功!"); } }

x

1 //StaticTest.java 2 public

class

StaticTest { 3

public

void

testNo (){ 4

System . out . println ( "没有Static测试成功" ); 5 } 6 7

public

static

void

testYes (){ 8

System . out . println ( "有Static测试成功!" ); 9 } 10 }

//StaticTestTest.java public class StaticTestTest{ public static void main(String[] args){ StaticTest test = new StaticTest(); test.testNo(); //StaticTest.testYes(); } }

1 //StaticTestTest.java 2 public

class

StaticTestTest { 3

public

static

void

main ( String [] args ){ 4

StaticTest

test

=

new

StaticTest (); 5

test . testNo (); 6

//StaticTest.testYes(); 7 } 8 } 注意看第二个文件 ,我们首先用正常的流程 创建对象>执行其方法 结果 没有Static测试成功

如果我们把创建对象的初始化语句注释掉会发生什么 public class StaticTestTest{ public static void main(String[] args){ //StaticTest test = new StaticTest(); StaticTest.testNo(); //StaticTest.testYes(); } }

x 1 public

class

StaticTestTest { 2

public

static

void

main ( String [] args ){ 3

//StaticTest test = new StaticTest(); 4

StaticTest . testNo (); 5

//StaticTest.testYes(); 6 } 7 } 执行结果 StaticTestTest.java:4: error: non-static method testNo() cannot be referenced from a static context StaticTest.testNo(); ^ 1 error 编译器报错 提示 testNo需要初始化调用

那么我们不想初始化对象也想调用其方法 该怎办

在StaticTest中以及预备好了代码 只需要在构造方法类型前面加上Static即可 public static void testYes(){ System.out.println("有Static测试成功!"); }

1 public

static

void

testYes (){ 2

System . out . println ( "有Static测试成功!" ); 3 }

测试一下 public class StaticTestTest{ public static void main(String[] args){ //StaticTest test = new StaticTest(); //test.testNo(); StaticTest.testYes(); } }

1 public

class

StaticTestTest { 2

public

static

void

main ( String [] args ){ 3

//StaticTest test = new StaticTest(); 4

//test.testNo(); 5

StaticTest . testYes (); 6 } 7 } 执行结果 有Static测试成功!

这样就体现出了Static的作用 尽管注释掉了初始化对象的语句 依然可以通过类名.方法名 调用方法