Abstraction and abstract in java

£可爱£侵袭症+ 提交于 2019-11-30 08:42:56

问题


I am a java developer with good understanding of Object orientation concepts(or maybe, I think like that). And right now I am learning design patterns (From Head first design patterns). I have been reading about OOPS concept abstraction to understand it briefly, and reading more about it has made me more confusing than I earlier was.

As I understand, abstraction refers to hiding the internal details of the program while exposing the interface to other programmers without worries of internal details. But, I don't understand

  1. How abstract classes fit into this concept of abstraction, where abstract class asks me to implement the abstracted method, where is abstraction in using abstract classes in java.
  2. I feel that, one way in which abstraction can be implemented is through private constructor and asking user of the class to use factory method to get the object of the class where you can implement and hide implementation details.

Please correct me, If I am wrong anywhere.


回答1:


"Abstract" is an antonym of "concrete". With abstractions you represent notions and ideas, rather than the concrete way these ideas are implemented. This fits into your understanding of abstraction - you are hiding the details and you only show the interface.

But this also fits with abstract classes - they are not concrete (they can't be instantiated, for one), and they don't specify implementations. They specify abstract ideas that subclasses have to take care of.

So it is basically a different point of view - one is from the point of view of clients of the API, and the other is also about subclasses. (Note that you can use abstract classes instead of interfaces in some cases to achieve the same effect, although it's not considered good practice)




回答2:


  1. The abstract classes defines an interface which the users of the class will use. An abstract class is similar to an interface except that some method can be implemented and all the abstracts ones will be implemented by the concrete classes that extends it. In summary the advantage is that you can have multiple implementations of the same abstract class that are completely interchangeable because the class that user operate with, is of the abstract type rather than of a specific implementation type.

  2. Using factory methods is an common approach for abstraction but you can also instantiate concrete class with their constructors. The important thing is the type of the variable that must be defined as the abstract type. Doing so the object variable can be accessed only with the interface defined by the abstract class.



来源:https://stackoverflow.com/questions/5443177/abstraction-and-abstract-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!