封裝、繼承和多態性是Java面向對象編程中的三大特性。封裝是使用類將對象數據和方法封裝在一起的機制,保證了數據不被惡意修改或誤操作。繼承是指通過擴展現有類來創建新類的過程,子類可以獲得父類的屬性和方法。多態性是指同一方法在不同的對象上表現出不同的行為。
//封裝 public class Student { private String name; //私有變量,外部無法直接訪問 private int age; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAge(int age) { if (age< 0) { //數據校驗 this.age = 0; } else { this.age = age; } } public int getAge() { return age; } } //繼承 public class Person { protected String name; //受保護的變量,子類可以直接訪問 protected int age; public void setName(String name) { this.name = name; } public String getName() { return name; } public void setAge(int age) { this.age = age; } public int getAge() { return age; } } public class Student extends Person { private String school; public void setSchool(String school) { this.school = school; } public String getSchool() { return school; } } //多態性 public abstract class Animal { public abstract void makeSound(); //抽象方法 } public class Dog extends Animal { public void makeSound() { System.out.println("汪汪汪"); } } public class Cat extends Animal { public void makeSound() { System.out.println("喵喵喵"); } } public class AnimalTest { public static void main(String[] args) { Animal animal1 = new Dog(); Animal animal2 = new Cat(); animal1.makeSound(); animal2.makeSound(); } }
Java的封裝、繼承和多態性讓程序更加模塊化和易于維護,是Java面向對象編程中的核心概念。