Java——静态方法使用注意事项

静态使用注意事项:

1,静态方法只能访问静态成员

非静态方法既可以访问静态也可以访问非静态。

2,静态方法中不可以定义this,super关键字

因为静态优先于对象存在。所以静态方法中不可以出现this。

3,主函数是静态方法。

class  StaticDemo
{
	public static void main(String[] args) //3
	{
		
		show();
	}
    public void show()
    {
        System.out.println("show....");
    }
}
/*
//1.
Exception in thread "main" java.lang.Error: 无法解析的编译问题:
	不能对类型 StaticDemo0 中的非静态方法 show()进行静态引用
*/
class Person
{
	String name;//成员变量,实例变量。随着对象的创建而存在于堆内存中
	static String country = "CN";//静态的成员变量,类变量。随着类的加载而存在于方法区中
	public static void show()
	{
		System.out.println("::::");
		//this.haha();//静态方法中不能出现this关键字2
	}
	public void haha()
	{
		System.out.println("hahaha...");
	}
}

class  StaticDemo
{
	public static void main(String[] args) //3
	{
		
		Person p = new Person();
		p.haha(); //对象调用成员方法
		Person.show();//类名调用静态方法,也可对象调用静态方法(不推荐)
	}
}
/*
hahaha...
::::
*/

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值