Java面向对象编程(OOP)主要通过以下四个特性来实现:
public class Person { private String name; private int age; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } extends来实现。public class Student extends Person { private String school; public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } } public interface Animal { void makeSound(); } public class Dog implements Animal { @Override public void makeSound() { System.out.println("Woof!"); } } public class Cat implements Animal { @Override public void makeSound() { System.out.println("Meow!"); } } public class Main { public static void main(String[] args) { Animal myAnimal = new Dog(); myAnimal.makeSound(); // 输出 "Woof!" myAnimal = new Cat(); myAnimal.makeSound(); // 输出 "Meow!" } } public abstract class Shape { private double x; private double y; public Shape(double x, double y) { this.x = x; this.y = y; } public abstract double area(); public abstract double perimeter(); } public class Circle extends Shape { private double radius; public Circle(double x, double y, double radius) { super(x, y); this.radius = radius; } @Override public double area() { return Math.PI * radius * radius; } @Override public double perimeter() { return 2 * Math.PI * radius; } } public class Rectangle extends Shape { private double width; private double height; public Rectangle(double x, double y, double width, double height) { super(x, y); this.width = width; this.height = height; } @Override public double area() { return width * height; } @Override public double perimeter() { return 2 * (width + height); } } 通过以上四个特性,Java面向对象编程可以实现代码的模块化、复用、扩展和维护。