JAVA 封装、继承、多态这三个概念请问你可以提供具体的例子并注明哪里是封装、继承、多态吗?
时间: 2023-07-10 10:29:26 浏览: 106
当然可以。以下是一个简单的Java例子:
```java
// 封装
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;
}
}
// 继承
public class Student extends Person {
private String school;
public String getSchool() {
return school;
}
public void setSchool(String school) {
this.school = school;
}
}
// 多态
public class Animal {
public void speak() {
System.out.println("Animal speaks.");
}
}
public class Cat extends Animal {
public void speak() {
System.out.println("Meow!");
}
}
public class Cow extends Animal {
public void speak() {
System.out.println("Moo!");
}
}
public class Main {
public static void main(String[] args) {
// 封装
Person person = new Person();
person.setName("Tom");
person.setAge(18);
System.out.println("Name: " + person.getName() + ", Age: " + person.getAge());
// 继承
Student student = new Student();
student.setName("Jerry");
student.setAge(20);
student.setSchool("ABC University");
System.out.println("Name: " + student.getName() + ", Age: " + student.getAge() + ", School: " + student.getSchool());
// 多态
Animal cat = new Cat();
Animal cow = new Cow();
cat.speak();
cow.speak();
}
}
```
在上面的例子中,Person类是一个封装的类,因为它将属性和方法封装在一个类中,并且使用getter和setter方法来控制属性的访问。Student类继承自Person类,因为它从Person类继承了属性和方法。Cat和Cow类都继承自Animal类,并且实现了speak()方法,这就是多态的体现。在main()函数中,我们创建了一个Animal类型的cat对象和一个Animal类型的cow对象,无论是Cat还是Cow类型的实例,都能够正确地调用它们的speak()方法。这就是多态的优点,它让我们的代码更加灵活和可扩展。
阅读全文