Java 类和对象应用技巧

封装与访问控制

封装是面向对象编程的核心原则之一,通过访问修饰符控制类成员的可见性。合理使用 privateprotectedpublic 可以增强代码安全性。

public class BankAccount {
    private String accountNumber;
    private double balance;

    public BankAccount(String accountNumber, double initialBalance) {
        this.accountNumber = accountNumber;
        this.balance = initialBalance;
    }

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public void withdraw(double amount) {
        if (amount > 0 && amount <= balance) {
            balance -= amount;
        }
    }

    public double getBalance() {
        return balance;
    }
}

继承与方法重写

继承允许子类复用父类的属性和方法,通过 @Override 可以重写父类方法实现多态。

class Animal {
    public void makeSound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    @Override
    public void makeSound() {
        System.out.println("Bark");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal myDog = new Dog();
        myDog.makeSound();  // 输出: Bark
    }
}

静态成员与静态方法

静态成员属于类而非实例,常用于工具类和常量。

class MathUtils {
    public static final double PI = 3.141592653589793;

    public static int max(int a, int b) {
        return a > b ? a : b;
    }
}

public class Main {
    public static void main(String[] args) {
        System.out.println(MathUtils.max(5, 10));  // 输出: 10
        System.out.println(MathUtils.PI);          // 输出: 3.141592653589793
    }
}

对象组合优于继承

通过组合其他类的对象来构建功能,比继承更灵活。

class Engine {
    public void start() {
        System.out.println("Engine started");
    }
}

class Car {
    private Engine engine;

    public Car() {
        this.engine = new Engine();
    }

    public void start() {
        engine.start();
    }
}

public class Main {
    public static void main(String[] args) {
        Car car = new Car();
        car.start();  // 输出: Engine started
    }
}

接口与抽象类

接口定义行为规范,抽象类提供部分实现。

interface Drawable {
    void draw();
}

abstract class Shape implements Drawable {
    protected String color;

    public Shape(String color) {
        this.color = color;
    }

    public abstract double area();
}

class Circle extends Shape {
    private double radius;

    public Circle(String color, double radius) {
        super(color);
        this.radius = radius;
    }

    @Override
    public void draw() {
        System.out.println("Drawing a " + color + " circle");
    }

    @Override
    public double area() {
        return Math.PI * radius * radius;
    }
}

public class Main {
    public static void main(String[] args) {
        Shape circle = new Circle("Red", 5.0);
        circle.draw();
        System.out.println("Area: " + circle.area());
    }
}

对象克隆

实现 Cloneable 接口并重写 clone() 方法可以实现对象复制。

class Person implements Cloneable {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return "Person{name='" + name + "', age=" + age + "}";
    }
}

public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Person original = new Person("Alice", 25);
        Person cloned = (Person) original.clone();
        System.out.println(cloned);  // 输出: Person{name='Alice', age=25}
    }
}

枚举类

枚举类型是特殊的类,适合表示固定数量的常量。

enum Day {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
}

public class Main {
    public static void main(String[] args) {
        Day today = Day.FRIDAY;
        
        switch (today) {
            case FRIDAY:
                System.out.println("Today is Friday!");
                break;
            default:
                System.out.println("Not Friday yet");
        }
    }
}

匿名内部类

适用于需要一次性使用的类实现。

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();  // 输出: Hello from anonymous class!
    }
}

泛型类

增加代码的类型安全性和复用性。

class Box<T> {
    private T content;

    public void setContent(T content) {
        this.content = content;
    }

    public T getContent() {
        return content;
    }
}

public class Main {
    public static void main(String[] args) {
        Box<String> stringBox = new Box<>();
        stringBox.setContent("Hello Generics");
        System.out.println(stringBox.getContent());  // 输出: Hello Generics
    }
}

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐