static静态方法

[b] static静态方法[/b]
1。在静态方法里只能直接调用同类中其它的静态成员(包括变量和方法)而不能直接访问类中的非静态成员这是因为对于非静态的方法和变量需要先创建类的实例对象后才可以使用而静态方法在使用前不用创建任何对象
2。静态方法不能以任何方式引用this 和super 关键字与上面的道理一样因为静态方法在使用前不用创建任何实例对象,当静态方法被调用时,this 所引用的对象根本就没有产生。
3。main()方法是静态的因此JVM在执行main方法时不创建main方法所在的实例对象因而在main()方法中,我们不能直接访问该类中的非静态成员必须创建该类的一个实例对象后,才能通过这个对象去访问类中的非静态成员

class student{
static String name = "姓名";//静态的成员变量
int age = 20;
static int count = 0; //静态的成员变量
student()//构造方法
{
System.out.println(count++);
}
static void stu(){
System.out.println(name);
// objstu(); 我们不能在静态的方法里去调用非静态的方法

}
void objstu(){
System.out.println("hao");
stu(); //可以在非静态方法里调用静态的方法
}
}
class teststudent{
public static void main(String[] args)
{
System.out.println(student.name);//可以直接访问类的成员
student st = new student();
st.stu();

System.out.println(st.name);

student.stu();//我们可以直接用.的方法直接调用静态的方法
new student().stu();
new student().stu();
new student().objstu();//可以直接用.的方法直接调用非静态的方法

}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值