java static 变量与方法

最近在看马士兵的java视频,看到static用法。总结如下:
static变量为静态变量,为类的公用变量,非静态和静态方法均可访问,可直接用类名+ . 调用。内存中存放data区域,仅有一份值。

static方法为静态方法,可直接类名+ . 也可以直接使用(比如main)。调用static方法时不会将对象的引用传给他,因此static方法不可访问非static变量。


public class ThisStaticDemo{
	String name;
    static int age;
	static int sid=100;
    public ThisStaticDemo (){ 
        this.age=21;
		sid++;
    }     
    public ThisStaticDemo(String name,int age){
		this();
        this.name="Mick";
    }     
	
	static void p(){
		System.out.println("我是静态方法");
		
	}
	private void print(){
		p();
		System.out.println(ThisStaticDemo.sid);
        System.out.println("最终名字="+this.name);
        System.out.println("最终的年龄="+this.age);
    }
    public static void main(String[] args) {
		p();
		System.out.println(ThisStaticDemo.sid);
		ThisStaticDemo tt=new ThisStaticDemo("",0); 
		tt.print();
    }
}

1、静态方法 p() 可在非静态方法print()和静态方法main()直接使用,无需创建对象引用。
2、静态变量 sid 可在非静态方法print()和静态方法main()直接调用,无需创建兑现给引用。

如果在将print()设置为静态方法,代码如下;

public class ThisStaticDemo{
	String name;
    static int age;
	static int sid=100;
    public ThisStaticDemo (){ 
        this.age=21;
		sid++;
    }     
    public ThisStaticDemo(String name,int age){
		this();
        this.name="Mick";
    }     
	
	static void p(){
		System.out.println("我是静态方法");
		
	}
	private static void print(){
		p();
		System.out.println(ThisStaticDemo.sid);
        System.out.println("最终名字="+this.name);
        System.out.println("最终的年龄="+this.age);
    }
    public static void main(String[] args) {
		p();
		System.out.println(ThisStaticDemo.sid);
		ThisStaticDemo tt=new ThisStaticDemo("",0); 
		tt.print();
    }
}

编译有以下错误:
java:21: 错误: 无法从静态上下文中引用非静态 变量 this
        System.out.println("最终名字="+this.name);
                                   ^
java:22: 错误: 无法从静态上下文中引用非静态 变量 this
        System.out.println("最终的年龄="+this.age);
                                    ^
2 个错误

-----------------

由于在代用static方法时,不会将引用传过来,因此无法访问非静态变量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值