43.static方法
- 静态方法,可以直接通过类名访问和调用
1)静态方法中不能使用this和super
2)不能直接访问所属类的实例变量和实例方法
3)可直接访问类的静态变量和静态方法
- 实例方法:通过实例访问
1)可直接访问所属的静态变量、静态方法、实例变量和实例方法
- 静态方法必须被实现
main()就是最常用的静态方法
注意:在实例方法中可以访问静态变量,但是不能定义静态变量
44.static方法总结
- 静态方法
- 可直接通过类名访问
- 不能直接访问所属类的实列变量和实例方法
- 可直接访问类的静态变量和静态方法
//Person类
package cn.com.ooa3.staticdemo;
public class Person {
//属性:成员变量,全局变量——————>实例变量
int age;
String name;
//静态变量——————>通过类名调用
static String email;
public void m2(){
System.out.println("实例方法m2");
}
//成员方法:实例方法->可以调用实例变量、实例方法、静态变量、静态方法
public void m1(){
/*//在实例方法中可以访问静态变量,但是不能定义静态变量
static String email12;X
*/
System.out.println(this.age);
System.out.println(email);
//this.m2();或者
m2();
m3();
}
//静态方法
public static void m3(){
/*//在静态方法中不能使用this
System.out.println(this.age);X
*/
/*//在静态方法中不能调用实例方法
m1();X
*/
/*//在静态方法中不能调用实例变量
System.out.println(age);X
*/
System.out.println("静态方法m3");
//在静态方法中能访问静态变量
System.out.println(email);
//在静态方法中可以调用静态方法
m4();
}
public static void m4(){
System.out.println("静态方法m4");
}
}
//TestPerson类
package cn.com.ooa3.staticdemo;
import java.util.Arrays;
public class TestPerson {
public static void main(String[] args) {
//调用类的成员变量(属性),创建对象,通过对象去访问——————>实例对象
Person p=new Person();
p.age=12;
p.name="李四";
//静态变量——————>通过类名调用
Person.email="ada@qq.com";
//p.email="ada@qq.com";
//通过实例调用实例方法
p.m1();
//通过类名调用静态方法
Person.m3();
/*//以前使用过的静态方法
Math.random();
Arrays.sort(a);
Arrays.binarySearch(a,key);*/
}
}
//Voter类
package cn.com.ooa3.staticdemo;
//模拟选民投票,每人一票,100截止
public class Voter {
//目前投票数,被所有选民实例所共享
static int count;
//投票总数最大值,到100时,就停止投票
static final int MAX_COUNT=100;
//选民名字
private String name;
public Voter(){}
public Voter(String name){
this.name=name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//选民投票
public void vote(){
if(count==100){
System.out.println("投票数已达到100,投票已停止!");
return;
}else{
count++;
System.out.println(this.name+"选民投票成功!当前投票总数为:"+count);
}
}
//显示当前投票总数
public static void showCount(){
System.out.println("当前的投票总数为:"+count);
}
}
//TestVoter类
package cn.com.ooa3.staticdemo;
public class TestVoter {
public static void main(String[] args) {
Voter v1=new Voter("张三");
v1.vote();
Voter v2=new Voter("李四");
v2.vote();
Voter v3=new Voter("王五");
v3.vote();
System.out.println("***********************************");
Voter.showCount();
for (int i=0;i<=97;i++){
Voter v=new Voter("v"+(i+1));
v.vote();
}
System.out.println("***********************************");
Voter.showCount();
Voter v4=new Voter("王麻子");
v4.vote();
System.out.println("***********************************");
Voter.showCount();
}
}