java如何使用class
使用 Class 的基本语法
在 Java 中,Class 是面向对象编程的核心概念,用于定义对象的属性和行为。以下是一个简单的 Class 定义示例:
public class Person {
// 属性(字段)
private String name;
private int age;
// 构造方法
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// 方法
public void introduce() {
System.out.println("Hello, my name is " + name + " and I am " + age + " years old.");
}
}
创建 Class 的实例
定义 Class 后,可以通过 new 关键字创建实例:
public class Main {
public static void main(String[] args) {
// 创建 Person 实例
Person person1 = new Person("Alice", 25);
Person person2 = new Person("Bob", 30);
// 调用方法
person1.introduce();
person2.introduce();
}
}
继承与多态
Java 支持继承,子类可以扩展父类的功能:
public class Student extends Person {
private String school;
public Student(String name, int age, String school) {
super(name, age); // 调用父类构造方法
this.school = school;
}
@Override
public void introduce() {
super.introduce(); // 调用父类方法
System.out.println("I study at " + school);
}
}
访问修饰符
Java 提供了访问控制修饰符来限制对 Class 成员的访问:
public: 任何地方均可访问。private: 仅限当前 Class 内部访问。protected: 当前 Class 及子类可访问。- 默认(无修饰符): 同一包内可访问。
静态成员
使用 static 关键字定义属于 Class 而非实例的成员:

public class MathUtils {
public static final double PI = 3.14159;
public static int add(int a, int b) {
return a + b;
}
}
// 调用静态方法
int sum = MathUtils.add(5, 3);
抽象类与接口
抽象类用于定义不能实例化的模板:
public abstract class Animal {
public abstract void makeSound();
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
接口定义行为规范:
public interface Drawable {
void draw();
}
public class Circle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}
内部类
Java 支持在 Class 内部定义其他 Class:

public class Outer {
private int outerField = 10;
public class Inner {
public void display() {
System.out.println("Outer field value: " + outerField);
}
}
}
// 使用内部类
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();
匿名类
适用于需要一次性使用的类实现:
interface Greeting {
void greet();
}
public class Main {
public static void main(String[] args) {
Greeting greeting = new Greeting() {
@Override
public void greet() {
System.out.println("Hello from anonymous class!");
}
};
greeting.greet();
}
}
Class 的常用方法
通过反射可以获取 Class 信息:
Class<?> personClass = Person.class;
System.out.println("Class name: " + personClass.getName());
System.out.println("Is interface: " + personClass.isInterface());
泛型 Class
使用泛型创建可重用组件:
public class Box<T> {
private T content;
public void setContent(T content) {
this.content = content;
}
public T getContent() {
return content;
}
}
// 使用泛型类
Box<String> stringBox = new Box<>();
stringBox.setContent("Hello");
Box<Integer> intBox = new Box<>();
intBox.setContent(123);






