Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

encapsulation and polymorphism

 
Angela lewis
Ranch Hand
Posts: 100
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is encapsulation and polymorphism and how does java use them?
thanks
 
KR Campbell
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Angela,

Data encapsulation and polymorphism are fundamental principles of object-oriented programming. To encapsulate something means to cover or surround it. In programming terms this means that direct access to data held within an object should be restricted. For example, if we have the following class:


If, from outside the class, we wish to access the value of number we have no choice but to use the method getNumber which is provided. This is because the access modifier has been set to private. We also have no way to alter this value because the programmer has decided not to provide a setNumber(int n) method. Therefore, access to the variable has been controlled and it is said to be encapsulated.

Polymorphism means that something can take many forms. In programming this means that it is possible using inheritance to generalise handling of different types of object and also deal with them at run-time. Here is an example of a class hierarchy:


Now we can make use of polymorphism:


Sorry, this was off the top of my head and is a bit crude, but the point is that we have a method, checkBerries() which takes a Plant parameter but which is capable of handling different types of plant. We don't have to write a checkBerries(Fuschia f) method and a checkBerries(Holly h) method.

The JVM is capable of distinguishing the two at run-time and calling the appropriate method from the appropriate class, so you can write code without knowing the exact type that will be passed into your program. The reference is to a Plant but the actual type of the objects are Holly and Fuschia respectively.

This is a very powerful mechanism which allows skilled programmers to write code which is very general and is thus much easier to re-use. For a good example, look at the Collection classes which generalise the handling of collections of objects.

HTH, although someone else might be able to provide a sharper answer.

Regards,
Ken
 
Charles Chen
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Encapsulation is the concept of hiding the internal details of something from the view of the user's of it.

Just like a class can be modified , maintained or extented without affecting the user, also the user can be modified, maintained or extented without affecting the internal details of the class.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic