java关键字,也叫保留字(50个),是java有特殊意义的标识符,不能用作参数名、变量名、方法名、类名、包名等。
现在我们讲讲其中三个关键字的使用吧~~~
【注】:this不能用于static方法中
/* * @Author: bpf * @Description: 测试this关键字 * @FilePath: /Learn in the Internet/Code/java/Test/TestThis.java */ public class TestThis { int index; int id; String name; String s = "Test <this> key word!"; TestThis() { System.out.println(s); } TestThis(int index, int id) { // TestThis(); // 调用构造方法不成功 this(); // 调用无参的构造方法 // index = index; // 此句无意义 this.index = index; this.id = id; } TestThis(int index, int id, String name) { this(index, id); // 使用this调用构造方法时必须是第一句 this.name = name; } public void showInfo() { System.out.printf( // 此句不加this效果一样 "%d - %d: %s/n", this.index, this.id, this.name); } public static void main(String args[]) { TestThis test1 = new TestThis(0, 10086, "中国移动"); test1.showInfo(); TestThis test2 = new TestThis(1, 10010, "中国联通"); test2.showInfo(); } }
/* * @Author: bpf * @Description: 测试static关键字 * @FilePath: /Learn in the Internet/Code/java/Test/TestStatic.java */ public class TestStatic { int index; String name; static String school = "Underwater School"; // 类变量 public TestStatic(int index, String name) { this.index = index; this.name = name; } public void welcome(int index, String name) { printSchool(); System.out.printf("Welcome NO.%d %s to Underwater School!/n", index, name); } public static void printSchool() { // 类方法 // welcome(this.index, this.name); // 不能在静态方法中调用非静态方法、非静态变量 // 不能在静态方法中使用this关键字 System.out.println(school); } public static void main(String args[]) { TestStatic stu = new TestStatic(1, "Jerry"); stu.printSchool(); stu.school = "Sky School"; stu.printSchool(); } }