The Magician and the custom class – understanding the header and implementation file - objective-c

I am taking my first stumbling steps in the Objective-C world together with a book on the subject. I have now come to the stage in which to internalize the concept of creating and using a custom class.
And as I guess that understanding these fundamental concepts and principles correctly is key to my future learning of Objective-C, I just wanted to check with you if have grasped the concepts somewhat correctly.
So when creating a custom class, I have understood that this is done in two separate files – the public class header file, and the class implementation file. And in order to internalize this concept, I have metaphorically understood this with a parallel to a “magician” doing its tricks in front of an audience.
The header file is somewhat like the poster outside the theatre where the magician performs. Before entering, we can all see what the magician looks like (the properties) and what tricks he (it’s mostly a “he”) can perform (the methods), and on what types of stuff he can make his magic tricks (type declaration). Thus from this “public” poster (the header file) of the magician, I can understand what kind of magic he can perform and what props he is using. Maybe there is also a mentioning of that this particular magician has learned some of his tricks from the great Houdini (the class heritage and Houdini thus being the superclass).
If I were allowed backstage, I would then be able to actually see how he is doing his tricks, that is, I would be able to look in the magicians implementation file.
Would this metaphor be somewhat along the lines of how you can understand the concept of a custom class?
However, I have not yet quite figured out how the concept of class methods and instance methods relates to this metaphor?
Could you say that instance methods belongs to a category of tricks that this particular “instance” of the magician is performing in this particular show, and the class methods would be the tricks that contemporary magicians can perform?
Thirdly, it is a bit confusing the way methods are using “types”. Some seem to be declared up front in the interface file, and some seem to just be “declared” on the fly within the methods?
To take an example using the “Magician” class, my understanding of the header file might look like this:
#interface Magician : NSHoudini
// Instance method that given a variable of type rat it will turn this into something of type rabit
- (rabit) FromRatToRabit: (rat) aRat;
#end
And the implementation file might look like this:
#import “Magician.h”
#implementation Magician
rabit aRabit
// rabit being the type and aRabit the variable
- (rabit) FromRatToRabit:(rat)aRat;
{
// some magic code goes here which will take what’s in the aRat variable, of type rat
// and turn it into a form of type rabit and return it in the aRabit variable
aRabit
}
#end
If above is correct I wonder why the aRat variable that you “feed” the method with is not declared? Or is the declaration considered done when you are using it in the method description?

Your metaphor is acceptable. A header is an interface for other files to look at which tell them what is accessible to them from that class/file and its corresponding implementation file (if it has one)
I noticed in your code though that Magician is a subclass of Houdini. I might just be misunderstanding your example, but in terms of inheritance, that is probably incorrect. What you are saying there is that every Magician is a type of Houdini. It should probably be reversed to say that Houdini is a type of Magician.
Class vs Instance has been explained many times and is not specific to Objective C, so I won't get into it too much.
Here is a post with some good answers. Basically, a class function/variable belongs to the Class itself, and is not specific to any instance of that class. Another word for a class function/variable is a static function or variable.
Not sure what you mean by the last question. Every pointer/variable in objective c has a type.
Your syntax is messed up though, Here is what the code you posted should probably look like (and yes I corrected the spelling of rabbit :-P)
#interface Houdini : Magician
// Instance method that given a variable of type rat it will turn this into something of type rabit
- (Rabbit *) FromRatToRabit: (Rat *) aRat;
#end
#import “Houdini.h”
#implementation Houdini
Rabbit *aRabbit; // this is an ivar, although you're not actually using it anywhere, I'm just correcting your syntax
- (Rabbit *) fromRatToRabit:(Rat *)aRat;
{
// some magic code goes here which will take what’s in the aRat variable, of type rat
// and turn it into a form of type rabit and return it in the aRabit variable
[aRat doSomethingToReturnRabbit]; // assuming rat has an instance function that returns a rabbit
}
#end
And you could use this function by doing something like
Houdini *myHoudini = [[Houdini alloc] init];
Rat *houdinisRat = [[Rat alloc] init];
Rabbit *houdinisRabbit = [myHoudini fromRatToRabbit:houdinisRat];
Note that this depends on there being a rat class and a rabbit class (which you did not provide). I am also just using what are normally the default initializers.
Hopefully this helps, you should try searching more on the specific topics you have questions on individually, because there is plenty of reading available.

It's a great metaphor for understanding the divide between the public interface and the hidden implementation. But I think you might be getting a bit wrapped up in it and I do see two major misunderstandings - "Houdini" being the superclass and the class methods being "all tricks".
The common textbook way to evaluate the sensibleness of an inheritance hierarchy is to evaluate whether a subclass instance "is a" superclass instance. This can get very abstract in reality but if, say, you're designing the Magician's Guild medical insurance benefits processing software or something, in that context a Magician "is a" something that's definitely not a Houdini! Say they are all freelancers so every Magician "is a" 1099 Contractor (US tax form for self-employment income), or something like that. Another way to think of it would be to think Magician "is a" Stage Performer, which "is a" Entertainer, and so forth. Not that you always want to make software like this but it can help for learning the concept I suppose.
The second thing you said you were struggling with was how to think about class methods. Consider class methods behavior and information inherent to the type, and independent of any instance. Going back to the benefits software example, lets say all Magician guild members get a 401k (another US tax code thing, retirement account) with $X defined contribution per paycheck. Now assuming that's not something that varies with seniority, this would be a good piece of information to keep at the class level. So, all the tricks a magician can perform would not be class methods - Magicians perform them, so they would be instance methods. Perhaps a list of banned tricks (for being too dangerous) could be a class method - it's a rule inherent to being a Magician but is independent from any single magician.
Finally, to your third question about types, I can sort of guess at what you're asking but am not sure. Say you have a method
- (void)myMethod:(id)myArgument
{
NSLog(#"myArgument = %#",myArgument);
}
Then are you asking where myArgument is declared? It is declared right there in the method signature, where it's a parameter to the method and you can refer to it in its scope of the method body (within the curly braces). Not sure if that's what you meant by "on the fly" or not. I'm afraid you'll have to provide some actual source code, not pseudocode, and point out specific places you're wondering about.
And a couple of minor points on terminology, sorry this is getting so long - the term for "feeding" a value to a method is "passing" usually as a "parameter" or an "argument". The method "description" is usually called a a method signature, or declaration, sometimes prototype I hear. And yes, please clarify what you're talking about with types, type declarations, and so on, I'm not 100% clear on your questions there.
Hope this helps!

Related

Stateless static methods vs. C functions in Objective-C

In terms of good Objective-C coding practices, if I create a function that has no state, is it better to write it as a static method of some class or as a C function?
For example, I have a special filepath retrieval method that checks the Caches directory before proceeding to the main NSBundle. I currently have it as a static method under an otherwise empty Utils class. Should this be a C function instead?
The reason I've chosen to use a static method (for now) is that a) it's consistent with Objective-C syntax, and b) the class helps to categorize the method. However, I feel like I'm cheating a little, since I could easily fill up my Util class with these stateless static methods and end up with an ugly "shell class", whose sole purpose would be to hold them.
What convention do you use? Is one "better" than the other, by some objective metric? Thank you!
If you can think of an existing class of which this might make a good method, you can inject your method into it by making an Objective-C category. This keeps your two reasons for using a static method while not polluting the class space with an extra class.
For example:
#interface NSString (MyStringCategories)
- (NSString*) myCoolMethod;
#end
// [StringCategories.m]
#import "StringCategories.h"
#implementation NSString (MyStringCategories)
- (NSString*) myCoolMethod {
// do cool stuff here
return whateverYouLike;
}
#end
Now you can send myCoolMethod to any string. Cool!
In your particular case, it sounds like a method on NSBundle might be an appropriate architecture. And don't forget, it can be a class method, so you don't need to instantiate anything in order to call your method.
This is quite a difficult question to answer because for a lot of people the answer will depend on what their personal preferences and tastes are. I personally think that if you have a function that is a function, i.e. it has nothing to do with an object, it has no internal state etc. pp. please let it be a function and do not try to wrap everything you possibly can into an object just because you are using an OO language and you can.
In order to keep my answer short let me refer to a (imo) quite good book:
http://www.gotw.ca/publications/c++cs.htm
I know that this is for C++, but there are quite a few insights that can be shared with other languages (esp. Objective-C and Objective-C++) especially from the part called "Class Design and Inheritance". There you will find an item titeled "Prefer writing nonmember nonfriend functions".
Bottom line: "Nonmember nonfriend functions improve encapsulation by minimizing dependencies[...] They also break apart monolithic classes[...] [and] improve genericity[...]".
I think there is quite some truth in that item.
If there's no class to clearly bind it to, then I use a function. I also use functions for these utility bits because they can be stripped if not used or referenced. In that regard, it's also helpful to use a function because a link error is better than a runtime error (in the even the .m was accidentally omitted from the build, or if was referenced from another externally updated method). One problem with ObjC symbols is that they do not get stripped, so they naturally carry a high amount of dependency -- all the objc methods and classes, and required category methods must exist in the final binary. That's not an issue with really small programs or libraries, but it quickly gains weight with medium/large systems and libraries.
Everything does not need to be declared in an #interface - especially with larger systems where all those declarations will really turn your interdependencies into spaghetti. Compared to methods, functions are faster, smaller, may be optimized better by the compiler or during linking, and may be stripped if not referenced.
If you need polymorphism, it just belongs in a class for organization or convenience, then a class or instance method is often a better choice.
I also minimize declaring category methods for the same reasons. When you're using functions, you can easily write a wrapper method where you need it and get the best of both worlds.

Objective C protocols usage

I have a homework question which confused me, really badly. Below is a brief explanation of a question.
Imagine you are developing an application that stores contact
information. The address book may contain many entity types e.g. Human
being, a company or anything else that has a contact information.
Now instead of explicitly checking every object type write a
protocol that declares how an object must behave and successfully
appear in your address book.
My understanding and efforts of answering this question is,
Build a protocol which has common methods of each type of contact information under #required tag. And all other methods which are not similar in different contact(Such as fax number has association with company but not person...) under #optional. At runtime you can check whether an object responds to any given method by using selector.
Doubt : However this is again explicitly checking object type indirectly, am I right?
My second thought is to use something like abstract class in java. Which means inherited class's from abstract class implements their own abstract methods. How ever as a naive iOS developer I don't know how to implement this? and I am not sure whether this is going to solve my problem. I would like get enlighten if someone knows this.
External Reading done so far, Please let me know if the answer I am looking for is in one of these links. I will read it again to understand and solve this :). thanks.
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html#//apple_ref/doc/uid/TP30001163-CH15-TPXREF144
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html#//apple_ref/doc/uid/TP30001163-CH15-TPXREF146
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Chapters/ocProtocols.html#//apple_ref/doc/uid/TP30001163-CH15-TPXREF149
A protocol is the same thing as a Java interface. It just defines which methods the class should support. Here's a page that explains it clearly: http://www.otierney.net/objective-c.html#protocols
Essentially if you want to make sure a class will have a phoneNumber method (accessor to the phoneNumber property) you would do something like this:
#protocol ContactProtocol
-(void) phoneNumber;
#end
#interface Person: NSObject <ContactProtocol> {
...
}
#interface Company: NSObject <ContactProtocol> {
...
}
And then at compile time (or live for xcode 4) it will tell you if you forgot to add the phoneNumber method to the Person or Company classes.
However this is again explicitly checking object type indirectly, am I right?
No, checking behavior is different from checking type. You can send -respondsToSelector: to any object, and if the result is YES you can send the message regardless of the object's type. You can also require that an object implement a given protocol, again without caring about its actual type:
id<SomeProtocol> foo; // foo points to any type that implements SomeProtocol
My second thought is to use something like abstract class in java.
That could work, but it's apparently not what your assignment asked for, right? It says "...write a protocol..."
Objective-C doesn't provide a way to explicitly make a class abstract the way Java does. You just create the class, and if you don't want it to be instantiated directly you document that somewhere.
You have ... options.
Optional methods are convenient for the person writing the class to conform to the protocol, annoying for the person making use of the protocol. So it depends who you are trying to please.
Optional methods are not as bad as checking type. Imagine how the code would look when accessing a contactable entity object. When you use an optional method, you have to have an if case and an else case. It's not as convenient as just going ahead and assuming you can call the method. But it's way more convenient than checking type. That would be one if case for each different type of entity (and an else case, which might be an assertion). Additionally, if you use optional methods, information about the entity is encapsulated in its class. If you check type before calling a method, then the information about what type of contact information an entity provides is outside the class in the calling code. If you upgrade the entity to provide an additional type of contact, that improvement is not available until you update the calling code.
Option B is to make all the methods required, but give them the option of returning a value that indicates that no information is available, such as nil. Of course that still means an if case to check for a nil result, it's just less verbose. An even better solution for this problem is to have the methods return collections of multiple contacts. After all, people can have more than one phone number. Then to indicate that a contact type is not applicable, you would just return an empty collection.
The downside is that whoever writes the class that conforms to the protocol has to add a simple stub method that says return nil or something.

When do I define objective-c methods?

I'm learning Objective-C, and have a C/C++ background.
In object-oriented C++, you always need to declare your method before you define (implement) it, even if it is declared in the parent class.
In procedural-style C, IIRC, you can get away with just defining a function so long as it is only called from something else in the same compilational unit (ie. the same file) that came later on in the file (well, provided you don't declare it elsewhere with "extern").
Now, in Objective-C, it appears that you only need to declare selectors in the header file if they are going to be used by something external, and that you can make up selectors in your .m file just fine, and call them within the .m file. Also, it appears that delegate methods or inherited methods are never (re)defined.
Am I on the right track? When do you need to define a selector in Objective-C?
For Objective-C methods, the general practice is to put methods you wish to expose in the #interface section of the header file so other code can include only the .h and know how to interact with your code. Order-based "lazy declaration" works just like functions in C — you don't have to declare a method prototype unless you have a dependency that can't be resolved by ordering, but you can add method prototypes inside the #implementation if needed.
So yes, you're on the right track. Don't repeat the method prototype for inherited methods — the compiler finds it in the parent's header file. Delegate methods may be defined as prototypes in a category (tacked onto a class) and implemented as desired, but the delegate does not need to provide a method prototype, since it is already defined. (It still can if it wants to for clarity, etc.)
Since you're just learning Objective-C, the rest of this answer is much more detail than you asked for. You have been warned. ;-)
When you statically type a variable (e.g. MyClass* instead of id) the compiler will warn you when you try to call a method that a class doesn't advertise that it implements, whether it does or not. If you dynamically type the variable, the compiler won't stop you from calling whatever you like, and you'll only get runtime errors if you call something that doesn't exist. As far as the language is concerned, you can call any method that a class implements without errors at runtime — there is no way to restrict who can call a method.
Personally, I think this is actually a good thing. We get so used to encapsulation and protecting our code from other code that we sometimes treat the caller as a devious miscreant rather than a trustworthy coworker or customer. I find it's quite pleasant to code with a mindset of "you do your job and I do mine" where everyone respects boundaries and takes care of their own thing. You might say that the "attitude" of Objective-C is one of community trust, rather than of strict enforcement. For example, I'm happy to help anyone who comes to my desk, but would get really annoyed if someone messed with my stuff or moved things around without asking. Well-designed code doesn't have to be paranoid or sociopathic, it just has to work well together. :-)
That said, there are many approaches for structuring your interfaces, depending on the level of granularity you want/need in exposing interfaces to users. Any methods you declare in the public header are essentially fair game for anyone to use. Hiding method declarations is a bit like locking your car or house — it probably won't keep everyone out, but (1) it "keeps honest people honest" by not tempting them with something they shouldn't be messing with, and (2) anyone who does get in will certainly know they weren't supposed to, and can't really complain of negative consequences.
Below are some conventions I use for file naming, and what goes in each file — starting from a .m file at the bottom, each file includes the one above it. (Using a strict chain of includes will prevent things like duplicate symbol warnings.) Some of these levels only apply to larger reusable components, such as Cocoa frameworks. Adapt them according to your needs, and use whatever names suit you.
MyClass.h — Public API (Application Programming Interface)
MyClass_Private.h — Company-internal SPI (System Programming Interface)
MyClass_Internal.h — Project-internal IPI (Internal Programming Interface)
MyClass.m — Implementation, generally of all API/SPI/IPI declarations
MyClass_Foo.m — Additional implementation, such as for categories
API is for everyone to use, and is publicly supported (usually in Foo.framework/Headers). SPI exposes additional functionality for internal clients of your code, but with the understanding that support may be limited and the interface is subject to change (usually in Foo.framework/PrivateHeaders). IPI consists of implementation-specific details that should never be used outside the project itself, and these headers are not included in the framework at all. Anyone who chooses to use SPI and IPI calls does so at their own risk, and usually to their detriment when changes break their code. :-)
Declaring the methods in the header file will only stop compiler warnings. Objective-C is a dynamic language, so you can call a method (send a message) to an object whether or not that method is declared externally.
Also, if you define a method in the .m file above any code that calls it (lazy declaration) then that won't generate any warnings. However the same thing applies, you can send a message to an object without it being declared.
Of course - this means that there are no private methods in Objective-C. Any method that a class implements can be called.
Personal preference. If it's a public method (i.e one used externally). declare it in the .h and define in the .m. If you want to limit it's visibility, or at least indicate that it is a private method, use categories/class extensions in the .m file. Although lots of example code uses the lazy declaration method.
Objective-C treats functions as "messages" and as such, you can send a "message" to any object - even one that doesn't explicitly state in its interface that it can accept. As a result, there are no such things as private members in Obj-C.
This can be very powerful, but is a source of confusion for new Obj-C programmers - especially those coming from C++, Java or C#. Here are the basic rules of thumb:
You should define all public methods in your #interface so that consumers know what messages you expect to handle.
You should define #private methods in your #interface to avoid compiler messages and avoid having to order the methods in your #implementation.
You should use protocols when implementing a particular convention of methods for your class.
Much of this is personal preference, however it helps to avoid annoying compiler warnings and keeps your code organized. and easy to understand.

Using "Base" in a Class Name

Is it acceptable to use the word 'Base' in a class name which is a the bottom of the inheritance tree?
I have always found this a bit of a cop-out, just wondering if anyone agrees with me.
For example, if I am refactoring certain elements from MyClassA and MyClassB into a common base class, I'd be tempted to create a MyBaseClass from which the two inherit.
But what happens if I ever need to refactor MyBaseClass? MyBaseBaseClass? Now that's just silly.
I know that Rocky Lhotka doesn't mind with his CSLA framework, but I'm always uneasy about 'definites' in programming.
Thoughts?
Let me clarify why I'm even worrying about this.
I have two namespaces - MySpecificNamespace and MyCommonNamespace. MyNamespace uses MyCommonNamespace, as you might expect.
Now, I like to make maximum use of Namespaces wherever possible to describe the context of the problem, and avoid adding the context to the class name. So, for example, consider that I have a class in MyNamespace which descends from one in MyCommonNamespace.
Option A
I could call this
MySpecificClass: MyClass
{
}
But then I'm adding 'Specific' (the context) to the name - which is redundant as it's already in MySpecificNamespace.
Option B
MyClass: MyCommonNamespace.MyClass
{
}
You can see how we could get confused here, right?
Option C
The one I think is fishy:
MyClass: MyBaseClass
{
}
I tend to add a Base suffix to the name of the base class only if it exists from technical perspective (to share some code), and doesn't really constitute any usable class on its own (so all of these classes are abstract). These are quite rare cases though, and should be avoided just as Helper classes.
"All your BaseClass are belong to us."
I side with a definitive no, with a single exception. If you are writing an app to manage military installations or baseball stadiums, go for it.
I side with "no" for exactly the refactoring reason you've cited.
A class should be named after what it logically represents, and nothing but the Object class is really really Base. Metaphysics ftw :)
re: Option B, there is nothing confusing about
namespace MySpecificNamespace
{
MyClass: MyCommonNamespace.MyClass
{
}
}
Classes that have the same name as their parent classes bug me to no end. In Java java.sql.Date extends java.util.Date. This is very annoying because you have to specify the exact class you want to import or else specify the classname fully (including package/namespace).
Personally I prefer to name things as they are; if a Base or Abstract class exists only to provide a partial implementation of something, and doesn't represent the interface for that thing, it is often acceptable to put the word Abstract or Base in its name. However, if that class represents the interface as well, then you should just name it after what it does.
For example, in Java, we have the Connection interface (for DB connections). It's just called Connection, not IConnection. You use it like this:
Connection con = getConnectionFromSomewhere();
If you are making a JDBC driver and need to implement connection, you could have a ConnectionBase or AbstractConnection which is the lower layer of the implementation detail of your particular Connection. You might have
abstract class AbstractConnection implements Connection
class OracleConnection extends AbstractConnection
or something like that. The clients of your code, however, never see AbstractConnection nor do they see OracleConnection, they only see Connection.
So, in general, classes that are meant to be generally useful should be named after what they represent/do, whereas classes that are helpers for code maintenance/organization can be named after what they are.
*ps I hate naming Interfaces with I. Do people name all their classes with C? It's 2009! your IDE can tell you what type of object that is, in the odd case when it even matters if it's an interface or a class.
I think it's worth wiki-fying this question.
FWIW, I agree. I usually try to find a more "generic" term for my base classes. So if I have a "Customer" class and need to introduce a new base class for it, I'd go with "Contact" or something rather than "CustomerBase".
I too would suggest No, but not cast in stone...
Following OO mantra, your naming system should best represent the underlying objects that the code is supposed to be encapsulating. There should really be no 'meta language', related to the actual syntactical makeup of the programming language of choice in there.
That said, if your object is truly abstract and you really don't see it changing anytime soon, there is an argument that adding 'Base' helps with general readability.
As with most things, there's no blanket right and wrong answer - it depends on the overall layout of your codebase, what this specific code is supposed to be representing and the in-house style that you have. Just try to be consistent.
Is base used anywhere else?
In Java I tend to provide a base implementation of an interface Foo in an abstract class FooBase. I think that is perfectly ok, and makes the connection to the interface very clear and regular.
Without the interface I would call the abstract base class Foo.
I also side with the no camp...place a Base in there today and in 6 months someone will whack a MyDerivedClass class in you code base while you're not looking.
"Abstract" prefix maybe?
I usually go with IFoo for the interface and AbstractFoo for the skeletal implementation, which is a mix of .NET and Java conventions.
I think it should probably be avoided where possible in favour of an identifier that actually describes what it is!
This question is difficult to answer because it's abstract. I might, for example, consider calling the base of MyClassA and MyClassB, "MyClass".
I agree, AbstractFoo is a decent solution. I try to pick names that don't need additional adjectives. I would shy away from using Base.
It seems like any principled answer will end up being no... However, comma, when I'm looking at code I'm not particularly familiar with, which happens a lot in python (where the source code is sometimes the only dependable documentation), I find it really helpful when a class has Base in it. Python is different from other OO languages where the class is defined with an "abstract" or "interface" specifier though. For naming, I like to ask myself "if I have never seen this code before, which way would make it easier for me to understand this code?" (Then, depending on how lazy I'm feeling, I name it accordingly).

What do you call a method of an object that changes its class?

Let's say you have a Person object and it has a method on it, promote(), that transforms it into a Captain object. What do you call this type of method/interaction?
It also feels like an inversion of:
myCaptain = new Captain(myPerson);
Edit: Thanks to all the replies. The reason I'm coming across this pattern (in Perl, but relevant anywhere) is purely for convenience. Without knowing any implementation deals, you could say the Captain class "has a" Person (I realize this may not be the best example, but be assured it isn't a subclass).
Implementation I assumed:
// this definition only matches example A
Person.promote() {
return new Captain(this)
}
personable = new Person;
// A. this is what i'm actually coding
myCaptain = personable.promote();
// B. this is what my original post was implying
personable.promote(); // is magically now a captain?
So, literally, it's just a convenience method for the construction of a Captain. I was merely wondering if this pattern has been seen in the wild and if it had a name. And I guess yeah, it doesn't really change the class so much as it returns a different one. But it theoretically could, since I don't really care about the original.
Ken++, I like how you point out a use case. Sometimes it really would be awesome to change something in place, in say, a memory sensitive environment.
A method of an object shouldn't change its class. You should either have a member which returns a new instance:
myCaptain = myPerson->ToCaptain();
Or use a constructor, as in your example:
myCaptain = new Captain(myPerson);
I would call it a conversion, or even a cast, depending on how you use the object. If you have a value object:
Person person;
You can use the constructor method to implicitly cast:
Captain captain = person;
(This is assuming C++.)
A simpler solution might be making rank a property of person. I don't know your data structure or requirements, but if you need to something that is trying to break the basics of a language its likely that there is a better way to do it.
You might want to consider the "State Pattern", also sometimes called the "Objects for States" pattern. It is defined in the book Design Patterns, but you could easily find a lot about it on Google.
A characteristic of the pattern is that "the object will appear to change its class."
Here are some links:
Objects for States
Pattern: State
Everybody seems to be assuming a C++/Java-like object system, possibly because of the syntax used in the question, but it is quite possible to change the class of an instance at runtime in other languages.
Lisp's CLOS allows changing the class of an instance at any time, and it's a well-defined and efficient transformation. (The terminology and structure is slightly different: methods don't "belong" to classes in CLOS.)
I've never heard a name for this specific type of transformation, though. The function which does this is simply called change-class.
Richard Gabriel seems to call it the "change-class protocol", after Kiczales' AMOP, which formalized as "protocols" many of the internals of CLOS for metaprogramming.
People wonder why you'd want to do this; I see two big advantages over simply creating a new instance:
faster: changing class can be as simple as updating a pointer, and updating any slots that differ; if the classes are very similar, this can be done with no new memory allocations
simpler: if a dozen places already have a reference to the old object, creating a new instance won't change what they point to; if you need to update each one yourself, that could add a lot of complexity for what should be a simple operation (2 words, in Lisp)
That's not to say it's always the right answer, but it's nice to have the ability to do this when you want it. "Change an instance's class" and "make a new instance that's similar to that one" are very different operations, and I like being able to say exactly what I mean.
The first interesting part would be to know: why do you want/need an object changes its class at runtime?
There are various options:
You want it to respond differently to some methods for a given state of the application.
You might want it to have new functionality that the original class don't have.
Others...
Statically typed languages such as Java and C# don't allow this to happen, because the type of the object should be know at compile time.
Other programming languages such as Python and Ruby may allow this ( I don't know for sure, but I know they can add methods at runtime )
For the first option, the answer given by Charlie Flowers is correct, using the state patterns would allow a class behave differently but the object will have the same interface.
For the second option, you would need to change the object type anyway and assign it to a new reference with the extra functionality. So you will need to create another distinct object and you'll end up with two different objects.