java——this 关键字及静态(static)属性/方法

一.this关键字

1.在构造方法中调用其他构造方法

调用构造方法时直接使用this(参数)

class Person{
	public String name;
	public Person(String n){
		name=n;
	}
	public Person(){
		this("陌生人");
	}
}

2.通过this访问属性或方法

访问普通方法时this.方法名称(参数)
访问属性时this.属性名
//访问普通方法
class Person{
	public String name;
	public Person(String n){
		name=n;
		this.toString();
	}
	public String toString(){
	}
}
//访问属性
class Person{
	public String name;
	public Person(String name){
		this.name=n;

	}
}
public class jk{
	public static void main(String[]args){
		Person p=new Person("张三");//需要在创建对象时,需要调用构造方法对类中的属性进行赋值
	}
}

3.this代表当前对象的引用

class Date{
	public Date after(){
		return this;
	}
}
public class Main{
	public static void main(String[]args){
		Date p=new Date();
		Date q=new Date();//创建了两个person类的对象,其引用指向了内存空间
		Date p1=p.after();//调用对象p的方法返回的是品对象的一个引用
		Date q1=q.after();
	}
}

例如我写一个Date类

class Date{
	public Date after(){
		return this;
	}
	public Date befor(){
		return this;
	}
}
public class Main{
	public static void main(String[]args){
		Date p=new Date(2019-7-21);//创建了两个person类的对象,其引用指向了内存空间
		Date p1=p.after(80);//调用对象p的方法返回的是品对象的一个引用
		Date q1=p1.befor(80);
	}
}//最终打印仍然为2019-7-21

二.静态类和属性

1.方法及属性的分类

  1. 方法:普通方法/静态方法

    2.属性:普通属性/静态属性

static 的含义是与对象解绑,即不再保存在对象(堆区),而是保存在类(方法区)中

static方法调用时的注意事项:

1.不能通过this访问
2.不能调用普通方法
3.不能访问普通属性
static 修饰的属性为静态属性存放在方法区,可以被任何方法访问

static类方法不能访问非静态类的属性/方法

非静态类方法允许访问static 类方法/属性 

2.访问静态属性/方法的方法

内部:1.属性名称/方法名称(实参)

     2.类名称.属性名称/类名称.方法名称(参数)

     3.this.属性名称/方法名称(参数)

外部:1.类名称.属性名称/方法名称(参数)

     2.引用.属性名称/方法名称(参数)
发布了40 篇原创文章 · 获赞 4 · 访问量 897

猜你喜欢

转载自blog.csdn.net/weixin_44919969/article/details/96766290