封裝、繼承和多態(tài)性是Java面向?qū)ο缶幊讨械娜筇匦浴7庋b是使用類將對(duì)象數(shù)據(jù)和方法封裝在一起的機(jī)制,保證了數(shù)據(jù)不被惡意修改或誤操作。繼承是指通過擴(kuò)展現(xiàn)有類來創(chuàng)建新類的過程,子類可以獲得父類的屬性和方法。多態(tài)性是指同一方法在不同的對(duì)象上表現(xiàn)出不同的行為。
//封裝 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) { //數(shù)據(jù)校驗(yàn) this.age = 0; } else { this.age = age; } } public int getAge() { return age; } } //繼承 public class Person { protected String name; //受保護(hù)的變量,子類可以直接訪問 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; } } //多態(tài)性 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的封裝、繼承和多態(tài)性讓程序更加模塊化和易于維護(hù),是Java面向?qū)ο缶幊讨械暮诵母拍睢?/p>