// Java关键字及其作用示例
// 1. public: 访问修饰符,表示公共的,可以被任何其他类访问
public class KeywordsExample {
// 2. static: 用于声明静态成员或方法,属于类而不是实例
public static void main(String[] args) {
// 3. final: 表示不可变,可用于类、方法和变量
final int MAX_VALUE = 100;
// 4. abstract: 抽象类或方法,抽象类不能实例化,抽象方法必须在子类中实现
// 下面是一个抽象类的定义
abstract class Animal {
abstract void makeSound();
}
// 5. interface: 接口定义,类可以通过实现接口来获得特定行为
interface Flyable {
void fly();
}
// 6. extends: 用于继承父类
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark");
}
}
// 7. implements: 用于实现接口
class Bird implements Flyable {
@Override
public void fly() {
System.out.println("Flying...");
}
}
// 8. new: 创建对象实例的关键字
Dog dog = new Dog();
dog.makeSound();
// 9. if-else: 条件语句
if (MAX_VALUE > 50) {
System.out.println("MAX_VALUE is greater than 50");
} else {
System.out.println("MAX_VALUE is not greater than 50");
}
// 10. for: 循环结构
for (int i = 0; i < 5; i++) {
System.out.println("Loop iteration " + i);
}
// 11. while: 另一种循环结构
int j = 0;
while (j < 3) {
System.out.println("While loop iteration " + j);
j++;
}
// 12. do-while: 先执行后判断的循环结构
int k = 0;
do {
System.out.println("Do-while loop iteration " + k);
k++;
} while (k < 2);
// 13. switch: 多分支选择结构
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
// 14. try-catch-finally: 异常处理结构
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed");
}
// 15. return: 返回方法的结果
int sum(int a, int b) {
return a + b;
}
// 16. this: 引用当前对象
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
// 17. super: 引用父类的对象或构造函数
class Parent {
Parent() {
System.out.println("Parent constructor called");
}
}
class Child extends Parent {
Child() {
super(); // 调用父类构造函数
System.out.println("Child constructor called");
}
}
// 18. synchronized: 用于线程同步
synchronized void syncMethod() {
// 同步代码块
}
// 19. volatile: 确保变量的修改对所有线程可见
volatile boolean flag = false;
// 20. transient: 标记不参与序列化的变量
transient int tempData = 0;
// 21. strictfp: 严格浮点模式
strictfp class StrictFpClass {
// 严格浮点计算
}
// 22. enum: 枚举类型
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}
// 23. package: 定义包名
package com.example.keywords;
// 24. import: 导入其他包中的类
import java.util.ArrayList;
// 25. assert: 断言,用于调试
assert true : "This should never happen";
}
}
上一篇:java报错找不到符号
下一篇:javalist排序sort降序
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站