数据抽象是只向用户显示基本细节的属性。不重要的或非重要的单元不会显示给用户。例:汽车被视为一辆汽车,而不是它的单个部件。
null
数据抽象也可以定义为只识别对象所需特征的过程,而忽略不相关的细节。对象的属性和行为将其与其他类似类型的对象区分开来,并有助于对对象进行分类/分组。
想想一个开车的人的真实例子。这名男子只知道踩下油门会提高车速,或者踩下制动器会使车速停止,但他不知道踩下油门时车速实际上是如何增加的,他不知道汽车的内部机制,也不知道油门、制动器等在汽车中的作用。这就是抽象。
在java中,抽象是通过 接口 和 抽象类 .我们可以使用接口实现100%的抽象。
抽象类和抽象方法:
- 抽象类是用 抽象关键词。
- 抽象方法是在没有实现的情况下声明的方法。
- 抽象类可能有也可能没有所有的抽象方法。其中一些可以是具体的方法
- 方法定义的抽象必须在子类中重新定义,因此 最重要的 强制或使子类本身抽象。
- 任何包含一个或多个抽象方法的类也必须用抽象关键字声明。
- 抽象类不能有对象。也就是说,抽象类不能直接用 新接线员 .
- 抽象类可以有参数化的构造函数,而默认构造函数总是存在于抽象类中。
什么时候用抽象类和抽象方法举例
在某些情况下,我们需要定义一个超类,它声明给定抽象的结构,而不提供每个方法的完整实现。也就是说,有时我们会想要创建一个只定义一个泛化形式的超类,该泛化形式将由它的所有子类共享,将其留给每个子类来填充细节。
考虑一个经典的“形状”例子,也许在计算机辅助设计系统或游戏模拟中使用。基本类型是“形状”,每个形状都有颜色、大小等。由此衍生(继承)出特定类型的形状——圆形、方形、三角形等等——每种形状都可能具有其他特征和行为。例如,某些形状可以翻转。某些行为可能会有所不同,例如,当您想要计算形状的面积时。类型层次体现了形状之间的相似性和差异性。
JAVA
// Java program to illustrate the // concept of Abstraction abstract class Shape { String color; // these are abstract methods abstract double area(); public abstract String toString(); // abstract class can have the constructor public Shape(String color) { System.out.println( "Shape constructor called" ); this .color = color; } // this is a concrete method public String getColor() { return color; } } class Circle extends Shape { double radius; public Circle(String color, double radius) { // calling Shape constructor super (color); System.out.println( "Circle constructor called" ); this .radius = radius; } @Override double area() { return Math.PI * Math.pow(radius, 2 ); } @Override public String toString() { return "Circle color is " + super .getColor() + "and area is : " + area(); } } class Rectangle extends Shape { double length; double width; public Rectangle(String color, double length, double width) { // calling Shape constructor super (color); System.out.println( "Rectangle constructor called" ); this .length = length; this .width = width; } @Override double area() { return length * width; } @Override public String toString() { return "Rectangle color is " + super .getColor() + "and area is : " + area(); } } public class Test { public static void main(String[] args) { Shape s1 = new Circle( "Red" , 2.2 ); Shape s2 = new Rectangle( "Yellow" , 2 , 4 ); System.out.println(s1.toString()); System.out.println(s2.toString()); } } |
输出
Shape constructor called Circle constructor called Shape constructor called Rectangle constructor called Circle color is Redand area is : 15.205308443374602 Rectangle color is Yellowand area is : 8.0
封装与数据抽象
- 封装 是数据隐藏(信息隐藏),而抽象是细节隐藏(实现隐藏)。
- 封装将数据和作用于数据的方法组合在一起,而数据抽象则处理向用户公开接口和隐藏实现细节的问题。
抽象的优点
- 它降低了观看事物的复杂性。
- 避免代码重复并提高可重用性。
- 有助于提高应用程序或程序的安全性,因为只向用户提供重要的细节。
相关文章:
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END