【Java】面向对象的三大特征:封装、继承、多态
封装(Encapsulation):
封装是将对象的状态(数据)和行为(方法)打包到一起,隐藏对象的内部实现细节,只提供公开的接口(getter和setter方法)供其他对象进行交互。
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = 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;
}
}
继承(Inheritance):
继承是子类继承父类的特性(包括数据和方法),并能扩展出新的能力。
public class Employee extends Person {
private double salary;
public Employee(String name, int age, double salary) {
super(name, age);
this.salary = salary;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
多态(Polymorphism):
多态是允许不同类的对象对同一消息作出响应。多态分为编译时多态(方法重载)和运行时多态(方法重写,父类引用指向子类对象)。
public class Animal {
public void makeSound() {
System.out.println("Animal makes a sound.");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Dog barks.");
}
}
public class TestPolymorphism {
public static void main(String[] args) {
Animal animal = new Dog(); // 父类引用指向子类对象
animal.makeSound(); // 输出 "Dog barks.",运行时多态
}
}
评论已关闭