Difference between "type", "instance", "class" and "object" concepts - terminology

I am trying to understand the concept of classes and objects, and I came across to the words "type" and "instance". Does type mean exactly the same thing as class, and instance for object? Or is there a difference in between, such as a usage difference etc.?

Quick Example
A class is the design specs for a MacbookPro, an instance is your MacbookPro specifically.
A type is just a class that defines your class, so that we can look at a blueprint and ask if design spec is MacbookProBlueprint. This is useful when we want meta-data about our classes (or other types). Think of a type as an Amazon.com entry, that would have lots of information about the MacbookPro such as processor speed and capabilities but not enough to actually build the object.
An object is your MacbookPro, or my car, or anything. Everything is an object which has implications larger than the scope of this question, but is fundamental nonetheless.

The SuperCollider book does a nice job of both summarizing programming concepts (particularly object oriented ones) and simultaneously demonstrating them in the SuperCollider language. See here for more information. It is a great resource, and the website has all of the code in a downloadable archive.

Related

What pattern/name should I use?

I have created a Singleton class that handles my project texts. What is the appropriate name of a Singleton class like this?
TextManager?
TextHandler?
TextController?
Is there a difference in meaning of these names?
UPDATE:
The class stores the project text as xml and have a method for returning the correct text.
function getText(uid : String) : String
I suppose it doesn't deal with adding/removing/... (-> managing) the texts (maybe just loading), so it isn't a "real" Manager.
It also doesn't "control" the texts (something "You're only accessible from ...", "Return another value for that key if ...").
The class provides you with texts.
I suppose it's some Kind of localized text provider, right?
So why don't you call it LocalizedTextProvider?
I usually call something like this
TextUtility
or
TextHelper
the problem with 'handler' is that it implies some sort of event handling. Same thing with 'Controller', it has meaning in a different context.
I believe Controller is 'reserved' for the MVC model but I may be wrong. TextHandler and TextManager may be better but at least at the place I work, 'Manager' in a service/class is generally discouraged since it is assumed that every class 'manages' something (this may just be culture-specific, though).
I'd vote for TextHandler out of those three. It may also depend slightly on your programming language.
This actually sounds like a service or repository to me...
TextService or TextRepository? TextModel?
But let me back up a bit... the Singleton pattern is a pretty bad way of accessing something like this. Just google "Singleton pattern problems" if you want to see what I am talking about. Plus, in AS3, you don't have private constructors so you can't implement the Singleton pattern in a pure way.
Instead, I really prefer composition via "Inversion of Control" (IoC) containers. There are plenty of them out there for ActionScript. They can be really lightweight but they decouple your components in a really elegant way.
Sorry to inject my thoughts here... ymmv :)
EDIT -- More on eliminating Singleton pattern
I have written about several strategies on eliminating singletons in your code. This article was written for C#, but all the same principles apply. In that article, I DON't talk explicitly about IoC containers.
Here is a pretty good article about IoC in Flex. In addition, several frameworks give you IoC capabilities:
Swiz
Robot Legs
fling
Cairngorm
flex-ioc
All three of the names you proposed can all be interpreted in the same way. Some people prefer handlers while others might say controllers... it really is a matter of semantics. Whatever convention you choose to adopt just be consistent. The common notion that you should capture though is that the class which you are describing is not doing anything. It should only be in charge of delegating, since that's what managers do to employees and controllers do in the classic MVC paradigm.
As I usually have Handler in the event/message handling context. Controller for actions and MVC stuff, I would go with something different:
TextResources.get(key)
I18n.get(key) (if your class is in fact used for internationalisation)
I usually reserve Helpers for classes allowing to simply transform some data into something to be used in the view.
TextCache? Sounds like you are just using it to store and retrieve data...
Why not : ProjectNameTexts
FooTexts.getInstance().getText('hello_world');

Why should you ever have to care whether an object reference is an interface or a class?

I often seem to run into the discussion of whether or not to apply some sort of prefix/suffix convention to interface type names, typically adding "I" to the beginning of the name.
Personally I'm in the camp that advocates no prefix, but that's not what this question is about. Rather, it's about one of the arguments I often hear in that discussion:
You can no longer see at-a-glance
whether something is an interface or a
class.
The question that immediately pops up in my head is: apart from object creation, why should you ever have to care whether an object reference is a class or an interface?
I've tagged this question as language agnostic, but as has been pointed out it may not be. I contend that it is because while specific language implementation details may be interesting, I'd like to keep this on a conceptual level. In other words, I think that, conceptually, you'd never have to care whether an object reference is typed as a class or an interface but I'm not sure, hence the question.
This is not a discussion about IDEs and what they do or don't do when visualizing the different types; caring about the type of an object is certainly a necessity when browsing through code (packages/sources/whatever form). Nor is it a discussion about the pros or cons about either naming convention. I just can't seem to figure out in what scenario, other than object creation, you actually care about wether or not you're referencing a concrete type or an interface.
Most of the time, you probably don't care. But here are some instances that I can think of where you would. There are several, and it does vary a little bit by language. Some languages don't mind as much as others.
In the case of inversion of control (where someone PASSES you a parameter) you probably don't care if it's an interface or an object as far as calling its methods etc. But when dealing with types, it definitely can make a difference.
In managed languages such as .NET languages, interfaces can usually only inherit one interface, whereas a class can inherit one class but implement many interfaces. The order of classes vs interfaces may also matter in a class or interface declaration. So you need to know which is which when defining a new class or interface.
In Delphi / VCL, interfaces are reference counted and automatically collected, whereas classes must be explicitly freed, so lifecyle management on the whole is affected, not just the creation.
Interfaces may not be viable sources for class references.
Interfaces can be cast to compatible interfaces, but in many languages, they cannot be cast to compatible classes. Classes can be cast to either.
Interfaces may be passed to parameters of type IID, or IUnknown, whereas classes cannot (without a cast and a supporting interface).
An interface's implementation is unknown. Its input and output are defined, but the implementation which creates the output is abstracted. In general, ones attitude may be that when working with a class, one may know how the class works. But when working with an interface, no such assumption should be made. In a perfect world, it might make no difference. But in reality, this most certainly can have affect your design.
I agree with you (and thereby do not use an "I" prefix for interfaces). We shouldn't have to care whether it is an abstract class or an interface.
Worth noting that Java needs to have a notion of interface solely because it does not support multiple inheritance. Otherwise, "abstract class" concept would suffice (which may be "all" abstract, or partially abstract, or almost concrete and just 1 tiny bit abstract, whatever).
Things that concrete class can have and the interfaces can't:
Constructors
Instance fields
Static methods and static fields
So if you use the convention of starting all interface names with 'I' then it indicates to the user of your library that the particular type will not have any of the above mentioned things.
But personally I feel that this is not a reason enough to start all interface names with 'I'. The modern IDEs are powerful enough to indicate if some type is an interface. Also it hides the true meaning of an interface name: imagine if Runnable and List interfaces were named IRunnable and IList repectively.
When a class is used, I can make the assumption that I will get objects from a relatively small and almost well-defined range of subclasses. That's because subclassing is - or at least it should be
- a decision that isn't made too easily, especially in languages that don't support multiple inheritance. In contrast, interfaces can be implemented by any class, and the implementation can be added later to any class.
So the information is useful, especially when browsing through code, and trying to get a feeling what the code author intended to do - but I think it should be enough, if the IDE shows interfaces/classes as distinctive icons.
You want to see at a glance which are the "interfaces" and which are the "concrete classes" so that you can focus your attention to the abstractions in the design instead of the details.
Good designs are based on abstractions - if you know and understand them you understand the system without knowing any of the details. So you know you can skip the classes without the I prefix, and focus on the ones that do have it while you are understanding the code, and you also know to avoid building new code around non-interface classes without having to refer to some other design document.
I agree that the I* naming convention is just not appropriate for modern OO languages, but truth is this question isn't really language agnostic. There are legitimate cases where you have an interface not for any architectural reason but because you simply don't have an implementation or have access to an implementation. For these cases you can read I* as *Stub or similar, and, in these cases, it might make sense to have an IBlah and a Blah class
These days, though, you rarely come up against this, and in modern OO languages when you say Interface you actually mean Interface not just I don't have the code for this. So there is no need for the I*, and in fact it encourages really bad OO design as you won't get the natural naming conflicts that would tell you something's gone wrong in your architecture. Say you had a List and an IList... what's the difference? when would you use one over the other? if you wanted to implement IList would you be constrained (conceptually at least) by what List does? I'll tell you what... if I found both an IBlah and a Blah class in any of my codebases I would purge one at random and take away that person's commit privileges.
Interfaces don't have fields, hence when you use IDisposable (or whatever), you know you're only declaring what you can do. That seems to me the main point of it.
Distinguishing between interfaces and classes may be useful, anywhere the type is referenced, in the IDE or out, to determine:
Can I make a new implementation of this type?
Can I implement this interface in a language that does not support multiple inheritance of implementation classes (e.g., Java).
Can there be multiple implementations of this type?
Can I easily mock this interface in an arbitrary mocking framework?
It is worth noting that UML distinguishes between interfaces and implementation classes. In addition, the "I" prefix is used in the examples in "The Unified Modeling Language User Guide" by the three amigos Booch, Jacobson and Rumbaugh. (Incidentally, this also provides an example why IDE syntax coloring alone is not sufficient to distinguish in all contexts.)
You should care, because :
An interface with capital "I" enables one, namely you or your co-workers to use any implementation which implements the interface. If in the future you figure out a better way to do something, say a better list sorting algorithm, you will be stuck with having the change ALL of the invoking methods as well.
It helps in understanding code - e.g. you don't need to memorize all 10 implementations of say, I_SortableList , you just care that it sorts a list (or something like that). Your code becomes practically self-documenting here.
To complete the discussion, here is a pseudocode example illustrating the above:
//Pseudocode - define implementations of ISortableList
Class SortList1 : ISortableLIst, SortList2:IsortableList, SortList3:IsortableList
//PseudoCode - the interface way
void Populate(ISortableList list, int[] nums)
{
list.set(nums)
}
//PseudoCode - the "i dont care way"
void Populate2( SortList1 list, int[] nums )
{
list.set(nums)
}
...
//Pseudocode - create instances
SortList1 list1 = new SortList1();
SortList2 list2 = new SortList2();
SortList3 list3 = new SortList3();
//Invoke Populate() - The "interface way"
Populate(list1,nums);//OK, list1 is ISortableList implementation
Populate(list2,nums);//OK, list2 is ISortableList implementation
Populate(list3,nums);//OK, list3 is ISortableList implementation
//Invoke Populate2() - the "I don't care way"
Populate(list1,nums);//OK, list1 is an instance of SortList1
Populate(list2,nums);//Not OK, list2 is not of required argument type, won't compile
Populate(list3,nums);//the same as above
Hope this helps,
Jas.

Is CouchDB best suited for dynamic languages?

I'm familiar with CouchDB and the idea of mapping its results to Scala objects, as well as find some natural way to iteract with it, came immediatly.
But I see that Dynamic languages such as Ruby and Javascript do things very well with the json/document-centric/shchema-free aproach of CouchDB.
Any good aproach to do things with Couch in static languages?
I understand that CouchDB works purely with JSON objects. Since JSON is untyped, it's tempting to believe that it's more naturally suited for dynamic languages. However, XML is generally untyped too, and Scala has very good library support for creating and manipulating XML. For an exploration of Scala's XML features, see: http://www.ibm.com/developerworks/library/x-scalaxml/
Likewise with JSON. With the proper library support, dealing with JSON can feel natural even in static languages. For one approach to dealing with JSON data in Scala, see this article: http://technically.us/code/x/weaving-tweed-with-scala-and-json/
With object databases in general, sometimes it's convenient to define a "model" (using, for example, a class in the language) and use JSON or XML or some other untyped document language to be a serialized representation of the class. Proper library support can then translate between the serialized form (like JSON) and the in-memory data structures, with static typing and all the goodies that come with it. For one example of this approach, see Lift's Record which has added conversions to and from JSON: http://groups.google.com/group/liftweb/msg/63bb390a820d11ba
I wonder if you asked the right question. Why are you using Scala, and not dynamic languages? Probably because of some goodness that Scala provides you that is important for you and, I assume, your code quality. Then why aren't you using a "statically typed" (i.e. schema-based) database either? Once again I'm just assuming, but the ability to respond to change comes to mind. Production SQL databases have a horrible tendency of being very difficult to change and refactor.
So, your data is weakly typed, and your code is strongly typed. But somewhere you'll need to make the transition. This means that somewhere, you'll have a "schema" for your data even though the database has none. This schema is defined by the classes you're mapping Couch documents onto. This makes perfect sense; most uses of Couch that I've seen have a key such as "type" and for each type at least some common set of keys. Whether to hand-map the JSON to these Scala classes or to use e.g. fancy reflection tools (slower but pretty), or some even fancier Scala feature that I'm yet new to is a detail. Start with the easy-but-slow one, then see if it's fast enough.
The big thing occurs when your classes, i.e. your schema, change. Instead of ALTER'ing your tables, you can just change the class, ensure that you do something smart if for some document a key you expect is missing (because it was based on an older version of the class), and off you go. Responding to change has never been easier, and still your code is as statically typed as it can get.
If this is not good enough for you, and you want no schema at all, then you're effectively saying that you don't want to use classes to define and manipulate your data. That's fine too (though I can't imagine a use), but then the question is not about dynamic vs static languages, but about whether to use class-based OO languages at all.

Theory, examples of reversible parsers?

Does anyone out there know about examples and the theory behind parsers that will take (maybe) an abstract syntax tree and produce code, instead of vice-versa. Mathematically, at least intuitively, I believe the function of code->AST is reversible, but I'm trying to find work/examples of this... besides the usual resources like the Dragon book and such. Any ideas?
Such thing is called a Visitor. Is traverses the tree and does whatever has to be done, for example optimize or generate code.
Our DMS Software Reengineering Toolkit insists on parsers and parser-inverses (called "prettyprinters") as "poker-ante" to mechanical processing (analyzing/transforming) of arbitrary languages. These provide full round-trip: source text to ASTs with captured position information (file/line/column) and comments, and AST to legal source text including regenerating the original token positions ("fidelity printing") or nicely formatted ("prettyprinting") options, including regeneration of the comments.
Parsers are often specified by a combination of grammars and lexical definitions of tokens; these notations are typically compiled into efficient parsing engines, and DMS does that for the "parser" side, as you might expect. Other folks here suggest that a "visitor" is the way to do prettyprinting, and, like assembly code, it is the right way to implement prettyprinting at the lowest level of abstraction. However, DMS prettyprinters are specified in terms of a text-box construction language over grammar terms something like Latex, that enables one to control the placement of the various language elements horizontally, vertically, embedded, spaced, concatenated, laminated, etc. DMS compiles these into efficient low-level visitors (as other answers suggest) that implement the box generation. But like the parser generator, you don't have see all the ugly detail.
DMS has some 30+ sets of these language front ends for a various programming langauge and formal notations, ranging from C++, C, Java, C#, COBOL, etc. to HTML, XML, assembly languages from some machines, temporaral property specifications, specs for composable abstract algebras, etc.
I rather like lewap's response:
find a mathematical way to express a
visitor and you have a dual to the
parser
But you asked for a sample, so try this on for size: Visual Studio contains a UML editor with excellent symmetry. The way both it and the editors are implemented, all constitute views of the model, and editing either modifies the model resulting in all remaining in synch.
Actually, generating code from a parse tree is strictly easier than parsing code, at least in a mathematical sense.
There are many grammars which are ambiguous, that is, there is no unique way to parse them, but a parse tree can always be converted to a string in a unique way, modulo whitespace.
The Dragon book gives a good description of the theory of parsers.
There are theory, working implementations and examples of reversible parsing in Haskell. The library is by Paweł Nowak. Please refer to
https://hackage.haskell.org/package/syntax
as your starting point. You can find the examples at following URLs.
https://hackage.haskell.org/package/syntax-example
https://hackage.haskell.org/package/syntax-example-json
I don't know where to find much about the theory, but boost::spirit 2.0 has both qi (parser) and karma (generator), sharing the same underlying structure and grammar, so it's a practical implementation of the concept.
Documentation on the generator side is still pretty thin (spirit2 was new in Boost 1.38, and is still in beta), but there are a few bits of karma sample code around, and AFAIK the library's in a working state and there are at least some examples available.
In addition to 'Visitor', 'unparser' is another good keyword to web-search for.
That sounds a lot like the back end of a non-optimizing compiler that has it's target language the same as it's source language.
One question would be whether you require the "unparsed" code to be identical to the original, or just functionally equivalent.
For example, would it be OK for the output to use a different indentation style than the original? That information wouldn't normally be stored in the AST because it's not semantically important.
One thing to look at would be automatic code refactoring tools.
I've been doing these forever, and calling them "DeParse".
It only gets tricky if you also want to recapture whitespace and comments. You have to tuck them into the parse tree so you can regenerate them on output.
The "Visitor Pattern" idea is good. But, I should consider "Visitor" pattern as a lineal list pattern, or, as a generic pattern, and add patterns for more specific cases like Lists, Matrices, and Trees.
Look for a "Hierarchical Visitor Pattern" or "Tree Visitor Pattern" on the web.
You have a tree data structure ("Collection") and want to do something with the data, each time you "visit", "iterate" or "read" an item from the tree.
In your case, you have a tree data structure, that represents the result of scanning/parsing some source code. Then you have read each item's data, and transform it into destination code.
There are several "lens languages" that allow bidirection transformation of source code.
It is also possible to implement reversible parsers using definite clause grammars in Prolog. In SWI-Prolog, the phrase/3 predicate converts parse trees into text and vice-versa. This book provides some additional examples of reversible parsing in Prolog.

What makes a language Object-Oriented?

Since debate without meaningful terms is meaningless, I figured I would point at the elephant in the room and ask: What exactly makes a language "object-oriented"? I'm not looking for a textbook answer here, but one based on your experiences with OO languages that work well in your domain, whatever it may be.
A related question that might help to answer first is: What is the archetype of object-oriented languages and why?
Definitions for Object-Orientation are of course a huge can of worms, but here are my 2 cents:
To me, Object-Orientation is all about objects that collaborate by sending messages. That is, to me, the single most important trait of an object-oriented language.
If I had to put up an ordered list of all the features that an object-oriented language must have, it would look like this:
Objects sending messages to other objects
Everything is an Object
Late Binding
Subtype Polymorphism
Inheritance or something similarly expressive, like Delegation
Encapsulation
Information Hiding
Abstraction
Obviously, this list is very controversial, since it excludes a great variety of languages that are widely regarded as object-oriented, such as Java, C# and C++, all of which violate points 1, 2 and 3. However, there is no doubt that those languages allow for object-oriented programming (but so does C) and even facilitate it (which C doesn't). So, I have come to call languages that satisfy those requirements "purely object-oriented".
As archetypical object-oriented languages I would name Self and Newspeak.
Both satisfy the above-mentioned requirements. Both are inspired by and successors to Smalltalk, and both actually manage to be "more OO" in some sense. The things that I like about Self and Newspeak are that both take the message sending paradigm to the extreme (Newspeak even more so than Self).
In Newspeak, everything is a message send. There are no instance variables, no fields, no attributes, no constants, no class names. They are all emulated by using getters and setters.
In Self, there are no classes, only objects. This emphasizes, what OO is really about: objects, not classes.
According to Booch, the following elements:
Major:
Abstraction
Encapsulation
Modularity
Hierarchy (Inheritance)
Minor:
Typing
Concurrency
Persistence
Basically Object Oriented really boils down to "message passing"
In a procedural language, I call a function like this :
f(x)
And the name f is probably bound to a particular block of code at compile time. (Unless this is a procedural language with higher order functions or pointers to functions, but lets ignore that possibility for a second.) So this line of code can only mean one unambiguous thing.
In an object oriented language I pass a message to an object, perhaps like this :
o.m(x)
In this case. m is not the name of a block of code, but a "method selector" and which block of code gets called actually depends on the object o in some way. This line of code is more ambiguous or general because it can mean different things in different situations, depending on o.
In the majority of OO languages, the object o has a "class", and the class determines which block of code is called. In a couple of OO languages (most famously, Javascript) o doesn't have a class, but has methods directly attached to it at runtime, or has inherited them from a prototype.
My demarcation is that neither classes nor inheritance are necessary for a language to be OO. But this polymorphic handling of messages is essential.
Although you can fake this with function pointers in say C, that's not sufficient for C to be called an OO language, because you're going to have to implement your own infrastructure. You can do that, and a OO style is possible, but the language hasn't given it to you.
It's not really the languages that are OO, it's the code.
It is possible to write object-oriented C code (with structs and even function pointer members, if you wish) and I have seen some pretty good examples of it. (Quake 2/3 SDK comes to mind.) It is also definitely possible to write procedural (i.e. non-OO) code in C++.
Given that, I'd say it's the language's support for writing good OO code that makes it an "Object Oriented Language." I would never bother with using function pointer members in structs in C, for example, for what would be ordinary member functions; therefore I will say that C is not an OO language.
(Expanding on this, one could say that Python is not object oriented, either, with the mandatory "self" reference on every step and constructors called init, whatnot; but that's a Religious Discussion.)
Smalltalk is usually considered the archetypal OO language, although Simula is often cited as the first OO language.
Current OO languages can be loosely categorized by which language they borrow the most concepts from:
Smalltalk-like: Ruby, Objective-C
Simula-like: C++, Object Pascal, Java, C#
I am happy to share this with you guys, it was quite interesting and helpful to me. This is an extract from a 1994 Rolling Stone interview where Steve (not a programmer) explains OOP in simple terms.
Jeff Goodell: Would you explain, in simple terms, exactly what object-oriented software is?
Steve Jobs: Objects are like people. They’re living, breathing things that have knowledge inside them about how to do things and have memory inside them so they can remember things. And rather than interacting with them at a very low level, you interact with them at a very high level of abstraction, like we’re doing right here.
Here’s an example: If I’m your laundry object, you can give me your dirty clothes and send me a message that says, “Can you get my clothes laundered, please.” I happen to know where the best laundry place in San Francisco is. And I speak English, and I have dollars in my pockets. So I go out and hail a taxicab and tell the driver to take me to this place in San Francisco. I go get your clothes laundered, I jump back in the cab, I get back here. I give you your clean clothes and say, “Here are your clean clothes.”
You have no idea how I did that. You have no knowledge of the laundry place. Maybe you speak French, and you can’t even hail a taxi. You can’t pay for one, you don’t have dollars in your pocket. Yet, I knew how to do all of that. And you didn’t have to know any of it. All that complexity was hidden inside of me, and we were able to interact at a very high level of abstraction. That’s what objects are. They encapsulate complexity, and the interfaces to that complexity are high level.
As far as I can tell, the main view of what makes a language "Object Oriented" is supporting the idea of grouping data, and methods that work on that data, which is generally achieved through classes, modules, inheritance, polymorphism, etc.
See this discussion for an overview of what people think (thought?) Object-Orientation means.
As for the "archetypal" OO language - that is indeed Smalltalk, as Kristopher pointed out.
Supports classes, methods, attributes, encapsulation, data hiding, inheritance, polymorphism, abstraction...?
Disregarding the theoretical implications, it seems to be
"Any language that has a keyword called 'class'" :-P
To further what aib said, I would say that a language isn't really object oriented unless the standard libraries that are available are object oriented. The biggest example of this is PHP. Although it supports all the standard object oriented concepts, the fact that such a large percentage of the standard libraries aren't object oriented means that it's almost impossible to write your code in an object oriented way.
It doesn't matter that they are introducing namespaces if all the standard libraries still require you to prefix all your function calls with stuff like mysql_ and pgsql_, when in a language that supported namespaces in the actual API, you could get rid of functions with mysql_ and have just a simple "include system.db.mysql.*" at the top of your file so that it would know where those things came from.
when you can make classes, it is object-oriented
for example : java is object-oriented, javascript is not, and c++ looks like some kind of "object-curious" language
In my experience, languages are not object-oriented, code is.
A few years ago I was writing a suite of programs in AppleScript, which doesn't really enforce any object-oriented features, when I started to grok OO. It's clumsy to write Objects in AppleScript, although it is possible to create classes, constructors, and so forth if you take the time to figure out how.
The language was the correct language for the domain: getting different programs on the Macintosh to work together to accomplish some automatic tasks based on input files. Taking the trouble to self-enforce an object-oriented style was the correct programming choice because it resulted in code that was easier to trouble-shoot, test, and understand.
The feature that I noticed the most in changing that code over from procedural to OO was encapsulation: both of properties and method calls.
Simples:(compare insurance character)
1-Polymorphism
2-Inheritance
3-Encapsulation
4-Re-use.
:)
Object: An object is a repository of data. For example, if MyList is a ShoppingList object, MyList might record your shopping list.
Class: A class is a type of object. Many objects of the same class might exist; for instance, MyList and YourList may both be ShoppingList objects.
Method: A procedure or function that operates on an object or a class. A method is associated with a particular class. For instance, addItem might be a method that adds an item to any ShoppingList object. Sometimes a method is associated with a family of classes. For instance, addItem might operate on any List, of which a ShoppingList is just one type.
Inheritance: A class may inherit properties from a more general class. For example, the ShoppingList class inherits from the List class the property of storing a sequence of items.
Polymorphism: The ability to have one method call work on several different classes of objects, even if those classes need different implementations of the method call. For example, one line of code might be able to call the "addItem" method on every kind of List, even though adding an item to a ShoppingList is completely different from adding an item to a ShoppingCart.
Object-Oriented: Each object knows its own class and which methods manipulate objects in that class. Each ShoppingList and each ShoppingCart knows which implementation of addItem applies to it.
In this list, the one thing that truly distinguishes object-oriented languages from procedural languages (C, Fortran, Basic, Pascal) is polymorphism.
Source: https://www.youtube.com/watch?v=mFPmKGIrQs4&list=PL-XXv-cvA_iAlnI-BQr9hjqADPBtujFJd
If a language is designed with the facilities specifically to support object-oriented programming(4 features) then it is an Object-oriented programming language.
You can program in an object-orientated style in more or less any language.It’s the code that is object-oriented not the language.
Examples of real object-oriented languages are Java, c#, Python, Ruby, C++.
Also, it's possible to have extensions to provide Object-Oriented features like PHP, Perl etc.
You can write an object-oriented code with C but it is not object-oriented prog. lang. It is not designed for that (that was the whole point of c++)
Archetype
The ability to express real-world scenarios in code.
foreach(House house in location.Houses)
{
foreach(Deliverable mail in new Mailbag(new Deliverable[]
{
GetLetters(),
GetPackages(),
GetAdvertisingJunk()
})
{
if(mail.AddressedTo(house))
{
house.Deliver(mail);
}
}
}
-
foreach(Deliverable myMail in GetMail())
{
IReadable readable = myMail as IReadable;
if ( readable != null )
{
Console.WriteLine(readable.Text);
}
}
Why?
To help us understand this more easily. It makes better sense in our heads and if implemented correctly makes the code more efficient, re-usable and reduces repetition.
To achieve this you need:
Pointers/References to ensure that this == this and this != that.
Classes to point to (e.g. Arm) that store data (int hairyness) and operations (Throw(IThrowable))
Polymorphism (Inheritance and/or Interfaces) to treat specific objects in a generic fashion so you can read books as well as graffiti on the wall (both implement IReadable)
Encapsulation because an apple doesn't expose an Atoms[] property