this关键字和static关键字

this

什么是this?
this是Java中的关键字,当前对象的引用。
this如何使用?

  1. 在实例方法中使用
public class ThisTest {
	int temp = 10;//成员变量
	public void a(){
		int temp = 20;//局部变量
		System.out.println(this.temp);//本类中的成员变量  输出10
		System.out.println("----------------------");
		System.out.println(temp);//输出20
	}
}
class Test{
	public static void main(String[] args) {
		ThisTest tt = new ThisTest();//创建对象
		tt.a();
	}
}

运行结果:
在这里插入图片描述
2. 在构造方法中使用

public class ThisTest {
	int temp = 10;//成员变量
	public ThisTest(int temp){
		this.temp = temp;//将传进来的值赋值给本类中的成员变量
	}
}
class Test{
	public static void main(String[] args) {
		//创建对象并调用该对象中需要传入一个int类型的值的构造方法
		ThisTest tt = new ThisTest(30);
		System.out.println(tt.temp);//输出30
		//这里的结果为啥是30呢,我上面明明定义的是10
		//因为在构造方法中使用了this.temp = temp; 将我们传入的30覆盖了原有的值了
	}
}

运行结果:
在这里插入图片描述


static

什么是static?
static也是Java中的一个关键字,表示静态的,它可以用来修饰变量、方法、等,修饰变量时叫静态变量,修饰方法时叫静态方法。
静态变量

public class Test {
	int a = 5;//(成员变量)全局变量
	static int b = 10;//静态变量
	//static的作用是共享给所有对象使用
	//静态变量一般很少用,一般和final一起使用用来声明常量
	final static int c = 20;	
	public static void main(String[] args) {
		Test t = new Test();//创建对象
		//要输出未加static的变量需要创建对象,使用对象名.变量名
		System.out.println(t.a);//输出5
		System.out.println(b);//输出10
		System.out.println(c);//输出20
	}
}

运行结果:
在这里插入图片描述
注意
在这里插入图片描述
静态方法

public class Test {
	//非静态方法
	public void method1(){
		System.out.println("非静态方法");
	}	
	//静态方法
	public static void method2(){
		System.out.println("静态方法");
	}	
	public static void main(String[] args) {
		Test t = new Test();//创建对象
		t.method1();//未加static的方法就算是在同一个类中,需要调用时也是要创建对象的
		method2();//加了static的方法可以直接使用方法名调用
		//Test.method2();//有两种写法  类名.方法名
	}	
}

运行结果:
在这里插入图片描述
注意
在这里插入图片描述
总结: 静态只能调用静态,非静态不仅可以调用非静态还可以调用静态,需要调用非静态的变量或方法需要创建对象,使用对象名.变量名或方法名。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值