static关键字的使用(一)

static方法与构造

静态方法一般不能调用任何非静态成员,却能调用非静态的构造

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package staticmethod;

public class Main {

public static void main(String[] args) {
// TODO Auto-generated method stub
StaticMethod aMethod=StaticMethod.newInstance();
System.out.println(aMethod);
}

}
class StaticMethod{
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public static StaticMethod newInstance(){

return new StaticMethod(1, "hhh");
}
private StaticMethod(){

}
@Override
public String toString() {
return "StaticMethod [id=" + id + ", name=" + name + "]";
}
private StaticMethod(int id, String name) {
super();
this.id = id;
this.name = name;
}
}

static方法与接口

接口中可以包含static方法了,但是必须有方法的实现,且调用方式有严格限制

1
2
3
4
5
6
public interface TestInter {
void printme();
static void print_s(){
System.out.println("print in static method in interface");
}
}

必须像下面这样调用

1
TestInter.print_s();
Donate comment here