JAVA基础-static,this关键字

本文详细介绍了Java中static关键字的使用,包括静态属性和静态方法的特点与调用方式,以及this关键字在类中的三种用途,帮助读者深入理解Java的类与对象概念。

static声明的属性为全局属性,声明的方法可以直接通过类名调用
使用static方法时,只能访问static声明的属性和方法,而非static声明的属性和方法是不能访问的

案例:

class Person{
	String name;
	 private static String country="北京";
	public Person(String name ) {
		this.name=name;
	}
	public void tell() {
		System.out.println(name+country);
	}
	public static String getCountry() {
		return country;
	}
	public static void setCountry(String country) {
		Person.country = country;
	}
}

因为country属性通过static关键字声明,因此使用set方法时也要加上static,并且可以通过类名Person直接调用

this关键字
1、表示类中的属性和调用方法
2、调用本类中的构造方法
3、表示当前对象

class People{
	private String name;
	private int age;
	public People(String name,int age){
		this();//必须放首行,直接调用构造方法
		this.name=name;//this调用当前类中的对象
		this.age=age;
	}
	public People() {
		System.out.println("无参数构造方法");
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public void tell(){
		System.out.println(this.getName()+this.getAge());//获取当前方法中的值
	}
}
public class Test04 {
	public static void main(String[] args) {
		People p=new People("张三",30);
		p.tell();
	}
}

输出结果:
无参数构造方法
张三30

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值