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

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

问题描述

我明白为什么我们需要Java中的抽象类 - 来创建子类。但同样可以通过具体类实现。例如类Child扩展父。这里父母可以很好地抽象&具体。那么为什么我们有ABSTRACT?

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意味着你不希望它被实例化,并且该类只能被继承。

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。如果你将一个函数或成员声明为私有的,你实际上保护它免受客户端代码的不当访问。私有意味着在类中使用,就是它。

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.

现在,您必须使用抽象类 并将函数和字段定义为private的公众? 否,您不。但是提供这些概念是为了帮助保持代码干净和组织良好。抽象类在所有面向对象的语言中实现我的知识。如果你看看周围你会看到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.

一个更好的,具体的例子:

A better, specific example:

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

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

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

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