[Java Review] 5: this and static

The following notes are based on video series: 手把手教你用Java基础教程 - 北京尚学堂 - 马士兵

this

Keyword this
  • In a method of a class , this refers to the object that uses the method.
  • Sometime it can be used to deal with the case that member varibales and method parameters have same names. (ref. uses the closest def.)
  • this can be view as a variable, whose value is the reference of the current object.

static

Keyword static
  • In a class, a static member variable is defined to be a shared variable for the class. When the class is first used, thestatic variable is initialized. For all the instance of the class, there is only one copy of this varible.
  • When a method is defined as static, this method, as it is called, will not parsed the ref. of the instance to the method, and hence will not able to use non-static variables.
  • We can use either instance ref. or class name (without a instance) to access static members.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// ex: use static var as counter

public class Cat{
private static int sid = 0;
private String name;
int id;
Cat(String name){
this.name = name;
id = sid++;
}
public void info(){
System.out.println
("My name is" + name + "No." + id);
}
public static void main(String arg[]){
Cat.sid = 100;
Cat mimi = new Cat("mimi");
Cat pipi = new Cat("pipi");
mimi.info();
pipi.info();
}
}
0%