java基础-关键字

Java关键字分类及用法

Java关键字是预定义的保留字,具有特定功能。以下是分类说明及示例:

访问控制关键字
  1. public
    允许跨包访问

    public class Main {
        public int publicVar = 10;
    }
    
  2. private
    仅当前类可见

    class Example {
        private String secret = "hidden";
    }
    
  3. protected
    同包或子类可见

    protected void display() {
        System.out.println("Protected method");
    }
    
类、方法和变量修饰符
  1. static
    属于类而非实例

    static int count = 0;
    static void printCount() {
        System.out.println(count);
    }
    
  2. final
    不可修改/继承

    final double PI = 3.14159;
    final class Immutable {}
    
  3. abstract
    抽象类/方法需被实现

    abstract class Shape {
        abstract void draw();
    }
    
程序控制关键字
  1. if-else
    条件分支

    if (score > 90) {
        grade = 'A';
    } else {
        grade = 'B';
    }
    
  2. switch-case
    多条件选择

    switch (day) {
        case 1: System.out.println("Monday"); break;
        default: System.out.println("Weekend");
    }
    
  3. for/while
    循环控制

    for (int i = 0; i < 5; i++) {
        System.out.println(i);
    }
    
错误处理关键字
  1. try-catch
    异常捕获

    try {
        int result = 10 / 0;
    } catch (ArithmeticException e) {
        System.out.println("Division by zero");
    }
    
  2. throw
    手动抛出异常

    if (age < 18) {
        throw new ArithmeticException("Not adult");
    }
    
  3. throws
    声明可能抛出异常

    void readFile() throws IOException {
        // 文件操作代码
    }
    
基本类型关键字
  1. int/double/boolean
    基本数据类型

    int age = 25;
    double price = 19.99;
    boolean isJavaFun = true;
    
  2. void
    无返回值方法

    void printHello() {
        System.out.println("Hello");
    }
    
变量引用关键字
  1. this
    当前对象引用

    class Person {
        String name;
        Person(String name) {
            this.name = name;
        }
    }
    
  2. super
    父类引用

    class Child extends Parent {
        Child() {
            super(); // 调用父类构造器
        }
    }
    
保留关键字
  1. goto/const
    保留未使用

    // 实际编程中不可用
    

关键注意事项

  • 所有关键字均为小写

  • 不能作为标识符使用

  • 部分关键字在不同上下文有不同作用(如final可修饰变量、类或方法)

通过合理组合这些关键字,可以构建完整的Java程序结构。实际开发中应根据需求选择适当的关键字来实现封装、继承和多态等特性。

posted @ 2026-09-28 23:29  程序员小小张  阅读(3)  评论(0)    收藏  举报