java基础-关键字
Java关键字分类及用法
Java关键字是预定义的保留字,具有特定功能。以下是分类说明及示例:
访问控制关键字
-
public
允许跨包访问public class Main { public int publicVar = 10; } -
private
仅当前类可见class Example { private String secret = "hidden"; } -
protected
同包或子类可见protected void display() { System.out.println("Protected method"); }
类、方法和变量修饰符
-
static
属于类而非实例static int count = 0; static void printCount() { System.out.println(count); } -
final
不可修改/继承final double PI = 3.14159; final class Immutable {} -
abstract
抽象类/方法需被实现abstract class Shape { abstract void draw(); }
程序控制关键字
-
if-else
条件分支if (score > 90) { grade = 'A'; } else { grade = 'B'; } -
switch-case
多条件选择switch (day) { case 1: System.out.println("Monday"); break; default: System.out.println("Weekend"); } -
for/while
循环控制for (int i = 0; i < 5; i++) { System.out.println(i); }
错误处理关键字
-
try-catch
异常捕获try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Division by zero"); } -
throw
手动抛出异常if (age < 18) { throw new ArithmeticException("Not adult"); } -
throws
声明可能抛出异常void readFile() throws IOException { // 文件操作代码 }
基本类型关键字
-
int/double/boolean
基本数据类型int age = 25; double price = 19.99; boolean isJavaFun = true; -
void
无返回值方法void printHello() { System.out.println("Hello"); }
变量引用关键字
-
this
当前对象引用class Person { String name; Person(String name) { this.name = name; } } -
super
父类引用class Child extends Parent { Child() { super(); // 调用父类构造器 } }
保留关键字
-
goto/const
保留未使用// 实际编程中不可用
关键注意事项
-
所有关键字均为小写
-
不能作为标识符使用
-
部分关键字在不同上下文有不同作用(如final可修饰变量、类或方法)
通过合理组合这些关键字,可以构建完整的Java程序结构。实际开发中应根据需求选择适当的关键字来实现封装、继承和多态等特性。
浙公网安备 33010602011771号