Java面向?qū)ο缶幊蹋∣OP)主要通過以下四個特性來實現(xiàn):
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
來實現(xiàn)。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面向?qū)ο缶幊炭梢詫崿F(xiàn)代碼的模塊化、復(fù)用、擴展和維護。