java抽象封装继承多态
时间: 2023-11-20 13:56:38 浏览: 191
Java中的四大特性是抽象、封装、继承和多态。其中,抽象类和接口是实现抽象的两种方式,而封装则是将数据和方法包装在一起,以保护数据不被外部直接访问和修改。继承则是通过子类继承父类的属性和方法,实现代码的复用和扩展。多态则是同一种行为具有多种不同表现形式或形态的能力。
具体来说,抽象类是一种不能被实例化的类,其中可以包含抽象方法和非抽象方法。抽象方法没有具体的实现,需要在子类中被实现。而非抽象方法则有具体的实现,可以被子类继承和重写。抽象类可以作为其他类的父类,子类需要实现其中的抽象方法才能被实例化。
封装则是将数据和方法包装在一起,以保护数据不被外部直接访问和修改。Java中可以使用private、protected和public三种访问修饰符来实现封装。private修饰的属性和方法只能在类内部访问,protected修饰的属性和方法可以在类内部和子类中访问,而public修饰的属性和方法可以在任何地方访问。
继承则是通过子类继承父类的属性和方法,实现代码的复用和扩展。Java中使用extends关键字来实现继承。子类可以继承父类的public和protected属性和方法,但不能继承private属性和方法。子类可以重写父类的方法,也可以使用super关键字调用父类的方法。
多态则是同一种行为具有多种不同表现形式或形态的能力。Java中通过继承和接口实现多态。具体来说,子类可以重写父类的方法,实现不同的行为表现形式。而接口则可以让不同的类实现相同的方法,实现不同的行为表现形式。
下面是一个简单的Java代码示例,演示了抽象、封装、继承和多态的使用:
```java
// 抽象类
abstract class Animal {
// 封装
private String name;
public Animal(String name) {
this.name = name;
}
// 抽象方法
public abstract void makeSound();
// 非抽象方法
public void eat() {
System.out.println(name + " is eating.");
}
}
// 继承
class Dog extends Animal {
public Dog(String name) {
super(name);
}
// 重写父类方法
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
// 多态
class AnimalSound {
public static void makeSound(Animal animal) {
animal.makeSound();
}
}
public class Main {
public static void main(String[] args) {
// 多态
Animal dog = new Dog("Buddy");
dog.makeSound(); // 输出:Woof!
dog.eat(); // 输出:Buddy is eating.
// 多态
AnimalSound.makeSound(dog); // 输出:Woof!
}
}
```
阅读全文
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)