java 关键字 this static

this关键字

this 的作用: 

this 表示的是当前对象本身 更准确的说,this代表当前对象的一个引用

普通方法中的this:

  • 区分类成员属性和方法的形参
  • 位置:任意

构造方法中的this:

  • 使用this 来调用其他构造方法
  • 位置:必须是第一条语句
public class TestThis {
	int a ,b,c; //成员变量

    TestThis(int a,int b ){
    	this.a = a;//区分了成员变量和局部变量
    	this.b = b;//this 的常用情况
   }
    TestThis(int a,int b,int c){
    	this(a,b); //调用构造方法,必须放在第一句
    	this.c = c;
    }
    void sing(){
    	
    }
    void dance(){
    	sing(); //调用本类中的sing()
    	System.out.println("边唱歌边跳舞");
    }
    public static void main(String[] args){
    	TestThis stu = new TestThis(2,3);
    	stu.dance();
    }
}

注意:static方法中不能用this

static关键字

static修饰的成员变量和方法,从属于类;普通变量和方法从属于对象

在类中,static声明的成员变量为静态成员变量,也称类变量 否则称为实例变量

实例变量和类变量(静态变量)区别:

1.不同对象的实例变量互不相同

2.所有对象共享类变量

3.通过类名直接访问类变量  类变量不仅可以通过某个对象访问,也可以直接用过类名访问

实例方法和类方法(静态方法)区别:

1.对象调用实例方法 实例方法中不仅可以操作实例变量也可操作类变量

2.类名调用类方法 实例方法不能通过类名调用,只能通过对象  类方法不可以操作实例变量

public class StaticTest {
	int id;
	String name;
	String pwd;
	static String company ="hp"; 
	public StaticTest(int id ,String name){
		
		this.id = id;
		this.name =name;
	}

	public void login(){
		printCompany();//实例方法可调用静态方法
		System.out.println("company");
		System.out.println("登陆"+name);
	}
	public static void printCompany(){
		// login(); //调用非静态方法报错
		System.out.println(company);
		
	}
	public  static void main(String[] args){
		StaticTest stu = new StaticTest(10001,"lee");
		stu.printCompany();
		stu.company="京东";
		stu.printCompany();
	}
}

本文仅用于自我学习,如有错误请指出,谢谢!

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值