请问上面的三种概念你有具体的例子吗
时间: 2024-03-03 10:48:47 浏览: 16
当然可以,我可以举一些具体的例子来帮助您理解封装、继承、多态的概念。
1. 封装的例子:
假设有一个汽车类Car,它有属性brand、model和price,以及方法start和stop。我们可以将属性和方法进行封装,使得外部只能通过公开的方法来访问和操作这些属性和方法。例如:
```java
public class Car {
private String brand;
private String model;
private double price;
public void start() {
System.out.println("The car has started.");
}
public void stop() {
System.out.println("The car has stopped.");
}
public void setBrand(String brand) {
this.brand = brand;
}
public void setModel(String model) {
this.model = model;
}
public void setPrice(double price) {
this.price = price;
}
public String getBrand() {
return brand;
}
public String getModel() {
return model;
}
public double getPrice() {
return price;
}
}
```
在这个例子中,属性brand、model和price被声明为private,只有Car类内部才能访问它们。外部只能通过公开的setter和getter方法来访问和修改这些属性。
2. 继承的例子:
假设有一个基类Animal,它有一个方法move用于描述动物的移动方式。我们可以从Animal类派生出一些子类,例如Bird和Fish,它们可以继承Animal类的move方法,并且可以添加自己的属性和方法。例如:
```java
public class Animal {
public void move() {
System.out.println("The animal is moving.");
}
}
public class Bird extends Animal {
private String color;
public void fly() {
System.out.println("The bird is flying.");
}
public void setColor(String color) {
this.color = color;
}
public String getColor() {
return color;
}
}
public class Fish extends Animal {
private String type;
public void swim() {
System.out.println("The fish is swimming.");
}
public void setType(String type) {
this.type = type;
}
public String getType() {
return type;
}
}
```
在这个例子中,Bird和Fish类继承了Animal类的move方法,并且添加了自己的属性和方法。因此,Bird和Fish类可以重用Animal类的代码,并且可以在此基础上进行扩展。
3. 多态的例子:
假设有一个基类Shape,它有一个方法getArea用于计算形状的面积。我们可以从Shape类派生出一些子类,例如Circle和Rectangle,它们分别重写了基类的getArea方法。例如:
```java
public class Shape {
public double getArea() {
return 0;
}
}
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
public class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
```
在这个例子中,Circle和Rectangle类重写了Shape类的getArea方法,并且使用不同的计算公式来计算面积。当我们定义一个Shape类型的变量,并且将它赋值为Circle或Rectangle类型的对象时,它可以根据对象的实际类型自动调用相应的getArea方法,从而实现了多态。例如:
```java
Shape s1 = new Circle(5);
Shape s2 = new Rectangle(3, 4);
System.out.println(s1.getArea()); // 输出78.53981633974483
System.out.println(s2.getArea()); // 输出12.0
```
在这个例子中,s1和s2都是Shape类型的变量,但是它们分别指向了Circle和Rectangle类型的对象。当我们调用它们的getArea方法时,会自动调用相应的子类方法,从而实现多态的效果。