抽象类与具体类有何不同? [英] How is abstract class different from concrete class?

查看:24
本文介绍了抽象类与具体类有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解为什么我们需要 Java 中的抽象类 - 创建子类.但同样可以通过具体类来实现.例如类 Child 扩展了 Parent.这里 Parent 很可能是抽象的 &具体的.那么为什么我们有抽象?

I understand WHY we need Abstract Class in Java - to create sub-classes. But the same can be achieved by concrete class. e.g. Class Child extends Parent. Here Parent can very well be abstract & concrete. So why do we have ABSTRACT??

推荐答案

抽象类不能直接实例化.将类声明为抽象类意味着您不希望它被实例化并且该类只能被继承.您正在代码中强加规则.

Abstract classes cannot be instantiated directly. Declaring a class as abstract means that you do not want it to be instantiated and that the class can only be inherited. You are imposing a rule in your code.

如果您进一步扩展您的父/子关系示例以包含一个 Person 类,那么将 Person 抽象化是很有意义的.父母是一个具体的想法,孩子也是.人在现实和代码中都是一个抽象的概念.

If you extend your Parent/Child relationship example further to include a Person class then it would make good sense for Person to be abstract. Parent is a concrete idea and so is child. Person is an abstract concept in reality as well as in code.

一个好处是您可以明确定义和保护抽象类的概念.当您将一个类声明为抽象类时,您或使用您的代码的任何其他人都无法通过实例化它来错误地使用它.这个推理类似于我们为什么将函数和字段指定为 public、private 或 protected.如果您将函数或成员声明为私有,您实际上是在保护它免受来自客户端代码的不当访问.Privates 是为了在课堂上使用,就是这样.抽象类是用来继承的,仅此而已.

One benefit is that you explicitly define and protect the idea of the abstract class. When you declare a class as an abstract there's no way that you or anyone else using your code uses it incorrectly by instantiating it. This reasoning is similar to why we specify functions and fields as public, private or protected. If you declare a function or member as private you are in effect protecting it from improper access from client code. Privates are meant to be used within the class and that's it. Abstract classes are meant to be inherited and that's that.

现在,您是否必须使用抽象类并将函数和字段定义为私有而不是公共?不,你没有.但是提供这些概念是为了帮助保持代码整洁和组织良好.据我所知,抽象类是在所有面向对象的语言中实现的.如果你环顾四周,你会发现 C++、C#、VB.NET 等都在使用这个概念.

Now, do you have to use abstract classes and define functions and fields as private instead of public? No, you don't. But these concepts are provided to help keep code clean and well-organized. The abstract class is implemented in all object-oriented languages to my knowledge. If you look around you will see that C++, C#, VB.NET etc. all use this concept.

一个更好的具体例子:

在上面的例子中,Shape 类应该是抽象的,因为它本身没有用.

In the example above the Shape class should be abstract because it is not useful on its own.

这篇关于抽象类与具体类有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆