this关键字的使用
this字面意思很好理解,表示这个的意思,放在java中作为一个关键字,而java又是面向对象开发的,所以我理解为“这个对象”,下面就简单举例说明下如何使用这个关键字:
1.将句柄返还给对象,经常用在return语句中
public class Leaf(){
private int i =0;
Leaf increment(){
i++;
return this; //此处就this意思就是返回此对象
}
void print(){}
public static void main(String[] args){
Leaf f = new Leaf();
f.increment().increment().increment().print() //这里就是多次通过对象调用方法
}
}
2.在构造器里调用构造器
注意:构造器之间不能相互调用、一个构造器里不能通过this调用两次
public class Flower{
Flower(){
this(5) // 这里通过this调用参数为int的构造器
this("string")//此处会报错,因为在构造器里只能通过this调用一个构造器
}
Flower(int i){
this("string")//这里通过this调用参数为string的构造器
}
Flower(String s){
this()//这里调用无参的构造器
this(5)//这里编辑器会报错,因为构造器互相调用
}
}
3.用在setter赋值上面等代表全局变量,用于区分本类成员变量赋值
static关键字
首先static字面意思是静态,用于修饰方法,参数等,也可以作为静态块,在static修饰的时候不存在对象,可通过类名.方法名()访问方法,类名.参数访问参数
其中使用static修饰的会优先加载(优先于构造器),比如
class Mug(){
Mug(){ System.out.println("Mug构造器")}
void f(int i){System.out.println("方法f()")}
}
class Mugs(){
Mug c1
{
c1 = new Mug();
}
Mugs(){
System.out.println("Mugs构造器");
}
public static void main(String[] args){
System.out.println("主方法");
Mugs x = new Mugs();
}
}
此处会打印出
//主方法
//Mug构造器
//Mugs构造器
不过此处的语句块里没加static,如果是static语句块,则会打印出一下输出
//Mug构造器
//主方法
//Mugs构造器
关于继承的一个坑
比如有一个父类A,子类B
public class A{
A(){}
}
public class B extends A{
B(int a){
//do something
}
}
这种写法没问题,但是如果父类里是一个有参数的构造方法,没有无参的情况
public class A{
A(int i){}
}
public class B extends A{
B(int i){} //此处就会报错,因为父类没有无参的构造方法,默认是找无参
//修改办法是给父类加个无参的构造方法或者使用super(1)去找指定的父类构造方法
}
***其中还有一点值得注意的是super和this在构造器中必须出现在方法体里的第一行,比如说
super() //编译能通过
this() //编译不能通过
反过来一样
this() //编译能通过
super() //编译不能通过
关于static与非static的理解误区
之前一直以为非static方法是不能出现在static方法里的,其实非也,虽然static方法中不能直接访问非static方法,但是可以在static方法中通过对象访问啊
class A{
void play(){}
static void doplay(A a){
a.play()//这里参数a是一个对象,通过对象来访问非static方法,此处是可以编译通过的
}
}
final在不同对象中的值
class A{
final int i1 = (int)(Math.random()*20);
static final int i2 = (int)(Math.random()*20);
void print(String id){
System.out.println(id+":i1="+i1+",i2="+i2);
}
public static void main(String[] args){
A a = new A():
a.print("1:");
A a1 = new A();
a1.print("2:");
}
}
//此时输出i1的两次值不相同,i2的两次值为相同的,这种是static与非static之间的差异