Question:
Can anyone explain encapsulation and Abstract concepts of oops ?
cute_22
2005-12-28 20:07:30 UTC
Can anyone explain encapsulation and Abstract concepts of oops ?
Five answers:
senthil
2005-12-28 21:46:50 UTC
Encapsulation is often confused with information hiding. However, these terms are not interchangeable. Encapsulation is the ability to bundle related data and functionality within a single, autonomous entity called a class. For example, a class called LoggerFile might bundle data members such as the log file's path; a buffer of data waiting to be written to that file; and member functions that open, read, write, and close that file, as in the following code listing:



class LogFile

{

public:

int Open();

int Read(char *buff);

int Write(const char *buff);

int Close();

private:

FILE *logfile;

bool _open;

//...additional data members

};In procedural languages such as C, you declare these data members and the associated functions separately. Consequently, a global function that opens a log file may be mistakenly called to open a file that has already been opened. Worse yet, users might delete a log file and then attempt to write to it. By bundling the data and functionality in an autonomous class, it's much easier to avert such human errors, because the class maintains the state of the file and is therefore able to prevent such errors.



Abstract classes can be used to define the C++ version of interfaces. A C++ abstract class describes functionality shared by objects of all concrete classes that are explicitly listed (perhaps indirectly) as subclasses. An object may play multiple roles by inheriting and implementing multiple interfaces. (The language doesn't directly support notions that an object may play different roles at different times, or that a role is implemented by a collection of objects, but these effects can usually be had in one way or another.)



C++ interface-style abstract classes take an idiomatic form:



class AnInterface {

public:

virtual T1 aService(T2, T3) = 0;

...

virtual T4 anAttribute() const = 0; // get value

virtual void anAttribute(T4) = 0; // set value

...

virtual T5 aReadOnlyAttribute() const = 0;



virtual ~AnInterface() {}



protected:

AnInterface() {}

};



Ideally, the types T should consist only of pass-by-value scalar types (int, float, enum, ...), collections of them (structs, ...) and/or pointers to objects of classes also defined via abstract classes (thus representing handles). The lack of native by-value string and array types in C++ is a problem here. One occasionally attractive alternative is to always contain fixed arrays in structs. But in practice, you can make ADT-style types work OK too. This way you can sometimes obtain simpler mechanics and also avoid value copying. ADT-style fake pointer classes may also be used instead of raw pointers for handle types, although there is no perfect way to do this.



Abstract classes sometimes lend themselves to parameterization over some type used in one or more signatures. (Some nice examples are described in Barton and Nachman's book.) Beyond the template prefix, nothing much changes except for the pragmatic problems of dealing with templates in C++. These include for example the fact that template instantiation errors are not usually reported until link time. This is best combatted by prefacing each template with a brief comment about what operations are assumed to be supported on the type (e.g., a < comparison).



Since interface classes cannot be directly instantiated, yet serve as virtual base classes for implementations, the constructors should take no arguments and should be listed as protected. Also, for similar reasons, abstract classes should have a no-op virtual destructor, not one listed as ... = 0. Depending on your compiler, you might need to define the no-op constructor and destructor operations outside the class declaration in a separate .C file.



The use of const here and elsewhere has its ups and downs. Officially, it is a good idea, since it helps enforce some of the intended semantic guarantees. But often enough, pragmatic concerns get in the way -- generally, const-ness propagates through all code that any implementations of the services touch. And C++ is sometimes too literal-minded about it to enforce it in a useful way. Sometimes (but only sometimes) it is better just to enforce these semantics manually. (In ADT-style classes, on the other hand, C++ const support tends to work pretty well and should almost always be used.)



Similar remarks hold, but moreso for exceptions. It is hardly ever a good idea to annotate a signature of a C++ abstract class with an exception list -- doing so commits all implementations to raise only the ones listed, which is often impossible to live with. Not listing any says implicitly that any exception may occur, thus requiring manual documentation about the ones that are likely.







Happy New Year !!!
Darrius
2005-12-28 20:22:56 UTC
When an object is highly encapsulated, it means that object provides just the services it needs, without exposing its inner workings to outer classes.



This is the main concept of oops - in procedural languages, you might have global variables, or functions that can be called from any point of the program.



The goal of oop is to rethink your design in terms of objects - entities that contain data and methods that work on that data. This data remains hidden and cannot be accessed by outside classes. Objects contain methods that manipulate this data, and only the ones needed by other classes are visible, others can be private.



This is of course, to achieve better code with less bugs - if things are hidden, then things cannot accidentally be changed.



Abstraction is the process of taking a problem domain and coming up with some model of it. Oop fascilates this because some problem domains work well in this fashion. A library database has books, people who check them out, librarians. This can all be abstracted by a collection of book objects, a collection of customer objects, etc.



A book object is an abstraction of a book in real life. You define what information you need it to contain, a title, who's checking it out perhaps, etc.



If you're talking about an abstract class, in oop its a class that has one or more methods that are undefined. Someone who wants to use the class has to extend the abstract class and implement the abstract methods.
?
2016-12-12 16:13:26 UTC
Explain Encapsulation
?
2016-11-11 07:40:57 UTC
To "Q & a guy": Your argument isn't very valid. whilst a woman has conceived a new child, the toddler, of course, isn't right this moment totally grown. It starts off as a fetus without all the actual structures which you will possibly see in a human. additionally, even whilst the youngster is born, it maintains to boost. the youngster even finally ends up with greater bones than it as quickly as had; particular applications of an toddler's recommendations get weaker as they grow previous too because of the fact they finally end up being out of date. As we boost, our cells continuously multiply inflicting us to get greater suitable in length, so the concept that all of us started from a single celled organism isn't too far fetched. to no longer point out, quite a few microorganisms that reason ailment evolve as our medicine gets greater stepped forward. it is all concerning to the organism adapting so as that it relatively is earlier than the sport and insure the continuation of the species. EDIT: yet another project that I forgot to show is that our "layout" isn't even faultless. we are at risk of mutations and ailments. additionally some areas of the physique are not relatively needed; there are some issues that our bodies won't be in a position to clearly recover from besides. Now to the question: the only part of the 'God concept' that seems smart is the "enable there be mild" project. maybe this replaced into probable the great bang. maybe this universe replaced into created by twist of destiny by way of some sensible beings or some organic occurring phenomenon. maybe it will ensue back. the assumption of an all-powerful being has basically stepped forward with mankind by way of the years to describe what could no longer be defined. Even now as quickly as we will not clarify some thing we affiliate it with issues that we are already acquainted with.
John C
2005-12-28 21:42:58 UTC
Encapsulation is a technique that helps information hiding. Encapsulation generally means access to data fields of objects and classes has been restricted - to classes or objects of the same type as the class the field is in, or sometimes including those of subclasses as well.



Note I can do away with some but not all of the benefits of encapsulation of a "private" field if I provide a getWhatever and a setWhatever method for each whatever field. At least I can still do cool things like be able to set a breakpoint or insert a logging statement/call which runs each time another class changes the field value. However, once they get that field's value, I can't tell if they will pass it around or let someplace else - anyplace else - in the software look at it, and perhaps change it.



Providing encapsulation encapsulation of all of your fields - and some of your methods - is often a good idea. It is usually even better to hide information about those encapsulated fields as well.



Encapsulation is a coding trick and is usually supported directly by a programming language. Information hiding is something you enforce with your design and is part of your programming style - or is not.



Abstraction is a different concept. Abstraction benefits from the use of encapsulation.



Abstraction makes use of the concept of "generalization" and the principle of "specialization".



To harness the power of abstraction, you pick a broad category of thing that different types of things in your application or system belong to. Let me give an example.



Maybe your system is a simulation. Lets say it simulates wolves and rabbits.



When rabbits get hungry, they stay in one place if there is grass there, and they chew it. If there is no grass there, they look for it, until they find it. If they see a wolf, they run and hide. If the fox finds them, they run and hide again. If a rabbit gets hungry while it is outrunning a fox, it doesn't matter - it ignores its hungry because not getting eaten by the fox is a higher priority.



When fox gets hungry, and it doesn't have a dead rabbit handy, it goes off and hunts for one. When it sees it, it chases it. If it gets away, it might wait a while to see if it comes out of cover or tries to detect its sent, but eventually it gives up if it doesn't find it.



To implement an object oriented program that implemented this, you could have an abstract Animal class that has a hungry flag. It could have an act() method that says:



IF hungry

IF foodHere()

eatFood()

ELSE

searchForFood()



Then you can create a Wolf subclass of Animal and a Rabbit subclass of Animal.



A rabbit's definition of the foodHere() method is going to check and see if there is grass nearby. A wolf's version of the method will check and see if there is a dead rabbit nearby.



A rabbit's version of searchForFood will go off and look for food. Unlike a wolf, a rabbit is not going to search the same place for grass that he found no grass earlier that same day - grass doesn't grow that fast. A rabbit will try to search as wide an areas as possible, if he runs out of grass nearby. If memory doesn't tell him where he saw some recently, he could look for it near running water, or he could do a spiral search. I do not know which of these techniques he uses, I am just illustrating that his need for different food demands a different way of looking for it than food.



A wolf on the other hand is seeking animal prey, not vegetation, and prey moves around - unlike vegetation. So a wolf will likely look in places where he has spotted and/or caught prey before. If he spots a place that has live grass and there is no live grass anywhere else, he will check there. Note, again, I am not a wolf, I am just giving this as an illustration - don't take it as fact that wolfs work exactly this way!



If a wolf smells the scent of a rabbit, he will follow the scent. Likewise, rabbit droppings' scent may lead it to rabbits as well. A wolf searching for a rabbit will try to kill it. Once a wolf has killed a rabbit, it no longer has to search. There is food now. That is how the wolf's version of the searchForFood() method needs to work.



In the Animal class, I would declare the searchForFood() method as abstract; I would not supply a definition for the logic to place in the method. This would force all concrete subclasses - e.g. the Rabbit and Wolf classes - to declare the method _and_ define the logic for it. Any subclass of Animal that does not provide a definition for how to do searchForFood would be "abstract". In order to be "concrete" it would have to provide a definition for it.





Another word for abstraction is generalization. Superclasses are usually more general than subclasses. Subclasses are usually specializations of their superclasses.



Another example that is less interesting but often used is that of shapes. Say you want to have a system that draws two types of shapes: Circle and Square.



Your application can have a Shape class. A shape must know its position. Lets say we declare a coordinate field in our Shape called "position". We define the position field with the value of the upper left corner of its shape. There must also be a size - more about that in a moment. The Shape class is abstract. It will declare one abstract method: draw().





Next, you have to write two subclasses of Shape, Square and Circle. Both of them are concrete, not abstract. Square accepts a size which it will use as the length of each of its 4 sides. Circle accepts a size which it will use as its diameter. They will accept this size value in their constructor, as well as the shape. Thus, each shape object will get its size and position defined when it is constructed.



Each Shape subclass will declare and define a draw() method.



For Square, this might look like:



drawRect(position.x, position.y, position.x+size, position.y+size);



For Circle, this might look like:



drawOval(position.x, position.y, position.x+size, position.y+size);



The classes are very similar. The definition of each draw method is very similar but each one is different in some specific way. Here, unlike the rabbit and wolf example, that similarity is very obvious. The difference too is very obvious. One calls drawRect, the other calls drawOval. Other than that, they are identical - they even pass the same arguments.



So, those are 2 sets of examples. The first example lets you define an abstract Animal class; the second one, an abstract Shape class.



Rabbit and Wolf are recognizably concrete things. You can visualize a rabbit and a wolf. Likewise, in a program, the rabbit and wolf objects could be constructed.



You cannot visualize an "animal" per se. Only specific types that are specific types of animal. Likewise, a program could not construct an animal object; it lacks a definition for searchForFood(). So the Animal class is abstract. It is suitable only as a template from which other types of Animal classes can be created. Wolf and Rabbit on the other hand are concrete. They can serve as templates for creating objects of their type.



Note that were squares, circles, rabbits, and wolves in the same program - there would be no reason for the code for a square class to look inside a rabbit and see if the rabbit was hungry.



So, it is possible to encapsulate the hungry field of Animal. It is possible to give it protected access because then our Shape class and its subclasses have no good reason to examine the field or change its value. It is beneficial to do so because then we can change the Rabbit, Animal, and Wolf class - and the Shape, Circle, and Square classes will require no change.



Encapsulation enforces disciplined, minimal access of the guts of one class to another. In the absence of encapsulation, classes can become mutually dependent. That means they all wind up depending on each other's guts. In this situation, changing any field name, for instance - might make you have to change the programming of all the other classes. Not fun. And not practical in a real world computer program.



I think you mean "OOP" not "oops". You say oops after a small disaster. You do OOP to avoid one. OOP stands for Object Oriented Programming.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...