淘先锋技术网

首页 1 2 3 4 5 6 7

封装、继承和多态性是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面向对象编程中的核心概念。