内部类
在Java中,内部类是定义在另一个类内部的类。内部类分为几种类型,包括成员内部类、静态内部类和匿名内部类。内部类可以访问外部类的成员,包括私有成员。
成员内部类
成员内部类是最普通的内部类,它是非静态的。从成员内部类中,可以直接访问外部类的所有成员。
示例:
public class OuterClass {
private int value = 10;
class InnerClass {
public void display() {
System.out.println("Value is: " + value);
}
}
public void createInner() {
InnerClass inner = new InnerClass();
inner.display();
}
}
public class Main {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
outer.createInner();
}
}
静态内部类
静态内部类是定义在另一个类内部的静态类。与成员内部类不同的是,静态内部类不能访问外部类的非静态成员。
示例:
public class OuterClass {
private static int value = 10;
static class InnerClass {
public void display() {
System.out.println("Value is: " + value);
}
}
}
public class Main {
public static void main(String[] args) {
OuterClass.InnerClass inner = new OuterClass.InnerClass();
inner.display();
}
}
匿名内部类
匿名内部类是没有名称的内部类。它们通常用于实现接口或继承类的一次性使用。
示例:
interface Greeting {
void sayHello();
}
public class Main {
public static void main(String[] args) {
Greeting greeting = new Greeting() {
@Override
public void sayHello() {
System.out.println("Hello, World!");
}
};
greeting.sayHello();
}
}
异常处理
异常是程序执行过程中发生的非正常情况。Java提供了强大的异常处理机制,允许你捕获和处理异常。
抛出异常
使用throw
关键字可以抛出一个异常。通常在方法中检测到错误时抛出异常。
示例:
public void checkAge(int age) throws Exception {
if (age < 18) {
throw new Exception("Access denied - You must be at least 18 years old.");
} else {
System.out.println("Access granted - You are old enough.");
}
}
捕获异常
使用try
和catch
块可以捕获并处理异常。finally
块可用于执行无论是否发生异常都需要执行的代码。
示例:
public class Main {
public static void main(String[] args) {
try {
checkAge(15);
} catch (Exception e) {
System.out.println("Caught an exception: " + e.getMessage());
} finally {
System.out.println("The 'try catch' is finished.");
}
}
public static void checkAge(int age) throws Exception {
if (age < 18) {
throw new Exception("Access denied - You must be at least 18 years old.");
} else {
System.out.println("Access granted - You are old enough.");
}
}
}
自定义异常
可以通过继承Exception
类或任何它的子类来创建自定义异常。
示例:
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
try {
throw new CustomException("This is a custom exception.");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
}
异常处理是Java编程的重要部分。它使得错误处理更加容易和集中,有助于提高程序的健壮性和用户体验。通过使用内部类和异常处理,Java开发者可以创建更加模块化和可维护的代码。