// Java关键字示例代码
// 1. 使用类和对象的关键字:class, new
class Example {
// 2. 使用访问修饰符关键字:public, private, protected
private int privateVar;
protected int protectedVar;
public int publicVar;
// 3. 使用构造函数和方法的关键字:this
public Example() {
this.privateVar = 0;
this.protectedVar = 0;
this.publicVar = 0;
}
// 4. 使用控制流的关键字:if, else, for, while, switch, case, break, default
public void controlFlowExample(int num) {
if (num > 0) {
System.out.println("Positive number");
} else if (num < 0) {
System.out.println("Negative number");
} else {
System.out.println("Zero");
}
for (int i = 0; i < 5; i++) {
System.out.println("For loop iteration: " + i);
}
int j = 0;
while (j < 5) {
System.out.println("While loop iteration: " + j);
j++;
}
switch (num) {
case 1:
System.out.println("Number is 1");
break;
case 2:
System.out.println("Number is 2");
break;
default:
System.out.println("Number is not 1 or 2");
}
}
// 5. 使用异常处理的关键字:try, catch, finally, throw, throws
public void exceptionHandlingExample() throws Exception {
try {
if (privateVar < 0) {
throw new Exception("Private variable is negative");
}
} catch (Exception e) {
System.out.println("Caught an exception: " + e.getMessage());
} finally {
System.out.println("Finally block executed");
}
}
// 6. 使用继承和多态的关键字:extends, implements, super, abstract, interface
public static class Animal {
public void makeSound() {
System.out.println("Animal sound");
}
}
public static class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Bark");
}
}
public static abstract class AbstractClass {
public abstract void abstractMethod();
}
public static interface Interface {
void interfaceMethod();
}
public static class ImplementingClass implements Interface {
@Override
public void interfaceMethod() {
System.out.println("Implementing interface method");
}
}
// 7. 使用包和导入的关键字:package, import
// 假设这个文件在 com.example 包中
// package com.example;
// import java.util.*;
// 8. 使用其他关键字:final, static, synchronized, volatile, transient
public final int FINAL_VAR = 10;
public static int STATIC_VAR = 20;
public synchronized void synchronizedMethod() {
// Synchronized block to ensure thread safety
}
public static void main(String[] args) {
Example example = new Example();
example.controlFlowExample(1);
try {
example.exceptionHandlingExample();
} catch (Exception e) {
e.printStackTrace();
}
Animal animal = new Dog();
animal.makeSound();
ImplementingClass implementingClass = new ImplementingClass();
implementingClass.interfaceMethod();
}
}
class 用于定义类,new 用于创建对象。public, private, protected 控制成员的可见性。this 引用当前对象实例。if, else, for, while, switch, case, break, default 用于控制程序流程。try, catch, finally, throw, throws 用于处理异常。extends, implements, super, abstract, interface 用于实现继承和接口。package, import 用于定义包和导入类库。final, static, synchronized, volatile, transient 用于不同的编程特性。上一篇:java 环境变量
下一篇:java获取当前时间年月日时分秒
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站