This question already has answers here:
Difference between object and instance
(15 answers)
Closed 9 years ago.
I have seen a lot of posts about objects, classes and instances and have become a little confused. I need clarification about the following example.
Say I create a game, it has three menus:
main menu,
level menu
option menu.
Now say I define a class called GameMenu since all these menus will have titles and instructions and buttons etc... Then I instantiate my menus using this class for example:
MainMenu = GameMenu();
LevelMenu = GameMenu();
OptionMenu = GameMenu();
And I pass the parameters for the titles and button labels and such inside the brackets - In the context of this example am I right in saying that my class is GameMenu, my objects are COLLECTIVELY MainMenu, LevelMenu and OptionMenu, and my instances are one specific object so MainMenu is an instance, OptionMenu is an instance and LevelMenu is an instance.
That is what I was taught, but that means objects and instances are the exact same things in which case the terms object and instance are synonyms for each other which is not what I have read?
Long story short, are object and instance terms synonyms?
An object is an instance of a class
Yes, you are right in saying so. Object and instance are synonyms.
http://en.wikipedia.org/wiki/Instance_(computer_science)
http://en.wikipedia.org/wiki/Object_(computer_science)
Object and instance can be used almost synonymously in the context of OOP, however instance is a more general term.
For example: an object is an instance off a class, and also a process is an instance of a program.
In practice, it sounds odd (to me at least) to refer to an object as an instance unless we are talking about it in terms of the class of which it is an instance.
With the following code:
Foo a = new Foo();
function int bar(Foo f) { return 0; }
I would say:
`Foo` is a class.
`a` is an object.
`a` is an instance of Foo.
Function `bar` accepts instances of the class `Foo`
Related
I know that for an instance variable all I have to do is put it inside the initialise method in the instance side and assign it a default value. But how I do this for class variable ? I tried to create an initialise method at class side but it did not give my variable a default value so I had to do this in one of my methods
pythonString ifNil:[pythonString := '']
But I don't like this approach.
I also found this for squeak , http://forum.world.st/Howto-initialize-class-variables-td1667813.html again I don't like this approach either. Is there a proper way of doing this. In Python it was fairly simple case of assignment why is it so cryptic for Pharo ?
First of all I hope that you are talking about instance variable of a class object (not a thing that you define on instance side as "class variable").
initialize is working, but it's being run upon instance creation. And instance (a class object) exists already when you define initialize method.
So when you define your class for the first time, you should run it by yourself e.g. YourClass initialize, bun later each time you load your class into system it should be initialised.
Let me consider following piece of code:
Person *peter = [people chooseRandomPerson];
where "people" is class instance, which was already initialised, and "chooseRandomPerson" is method which returns object of "Person" type. I wonder if it's the same as following:
Person *peter = [[Person alloc] init];
peter = [people chooseRandomPerson];
If not, what is the difference. If not, can I use such a substitution anytime? I am sorry, if the question is elementary, but I wasn't able to find an answer.
The second creates an object, puts it into the variable peter, and then immediately discards it* to store the return value of chooseRandomPerson.
The variable peter is a place to put a thing; the object is the thing you get back from the alloc/init or the chooseRandomPerson. You don't need to create a thing in order to have a place to put it; the declaration Person *peter; creates the place -- the variable -- by itself.
*If you weren't using ARC, this would be a leak, but if you're asking this you'd better be using ARC.
The answer by Josh Caswell is correct. But your question is not entirely clear.
In your question, you never define what is "people". You say "class instance" by which you presumably meant "object". But an object/instance of what class? Using the plural word "people" suggests a collection of objects. You should clarify this in your question.
Object Creating Sibling Objects
If you are asking "Can an object return a new instance of its own class?", the answer is "Yes". In your example, "peter" a Person object can produce a new Person object, "Sally".
However, an object creating sibling objects (new objects of the same class) is somewhat unusual in my experience. More common would be a using the Factory design pattern to produce instances.
There is one common use of an object creating sibling objects: Immutable objects. Instead of changing one field of data in a DateTime object, an entirely new object is created with most of its data based on the original.
This question already has answers here:
Create a subclass of a class using parent's init - from another class
(2 answers)
Closed 8 years ago.
EDIT: Yes, I did it wrong. It's well possibly knowing the init method by using a protocol on class level. This is something I rarely do, so that didn't come to my mind at first (see linked question about my answer to it using a protocol). So yes, this question is broken. As bbum said, there should be absolutely no reason to do this.
Background to my question in [1].
For a design reason (data mapper pattern) I need to initialize classes which I know are subclasses of a certain base class (ManagedEntity). I assert for this once - then later I want to create as many instances, and as fast as possible (I'm programming for iOS). However, since the class where I need to create the concrete instances in doesn't know any of the model classes, the meta class stored and used to create entity instances of is just known to be of type Class.
Long story short: I can't simply use [[[_EntityClass] alloc] initWithBlah:something], since EntityClass is unknown, just known as type Class there, hence the init method initWithBlah is unknown of course - but I know it must exist (it must be by design a subclass of the base class, which is asserted once when the mapper is initialized).
So in order to create instances of the unknown class with the init method that I know it exists, I need to construct a method invocation. This should call the initWith:something selector on the unknown class and create an instance of it.
I think I should use objc_msgSend rather than NSInvocation, because the latter is supposed to be an order of magnitude slower [2]. The init method is supposed to not change, and requires one argument.
So... What would be the equivalent to:
ManagedEntity *newEntity = [[ManagedEntity] alloc] initWithEntityDescription:_entityDescription];
with objc_msgSend?
[1] Create a subclass of a class using parent's init - from another class
[2] http://www.mikeash.com/pyblog/performance-comparisons-of-common-operations-leopard-edition.html
Better:
Class klass = NSClassFromString(className);
id newEntity = [[klass alloc] initWithEntity:entity insertIntoManagedObjectContext:ctx];
There is no reason to use objc_msgSend() directly when you have a fixed selector. You can always call the selector directly using the normal syntax. Worst case, you might have to type-cast the return value of one of the calls.
The only requirement is that the compiler has seen the declaration of initWithEntity:insertIntoManagedObjectContext: sometime prior to compiling the above call site.
Example:
#interface NSObject(BobsYourUncle)
- (void)bob:sender;
#end
...
Class klass = NSClassFromString(#"NSManagedObject");
[[klass alloc] bob:nil];
The above compiles just fine. Not that I'd recommend hanging random definitions off of NSObject. Instead, #import the abstract superclass's declaration (which should contain the selector declaration).
id cls = NSClassFromString(className);
id alloced_cls = objc_msgSend(cls, #selector(alloc));
id newEntity = objc_msgSend(alloced_cls, #selector(initWithEntity:insertIntoManagedObjectContext:), entity, ctx);
return newEntity;
What is the basic differences between an Instance and an Object of the class? I always have confusion about how exactly they are different.
An instance is an object in memory. Basically you create object and instantiate them when you are using them.
Here is a nice article on Classes Vs Objects Vs Instances, he is talking Java but it applies to all object oriented programming:
Class vs Object vs Instance
What is the difference between 'human' and 'you'?
'Humans' is a class (there are a lot of humans), but 'you' are only one (you are an object of human).
What is instance? There are some functions, which works not only for objects, but for class too. Examples: human::isMammal() == true, human::isArachnid() == false. You don't need an object of class human to call such functions (because these function don't use any special properties of objects: all humans are mammals and not arachnid), so it is enough to work with instance.
To be simple,
Object is an instance of the class.
When people talk about object, it is more specific to a particular instance (values in variables in the class). I hope, I have at-least not confused you.
I think most programmers would use "object" and "instance" interchangeably. Some pedants may try to draw distinctions, but such distinctions are meaningless if they are not recognized by the majority of users of the terms.
"Class", of course, is a sort of template or design for an object.
An object is the definition of something while an instance is a manifestation if that thing. As an example, a chair by definition has a seat, 3 or more legs and a back. This would be the object. Note, we only have a definition and not an object itself. Now if we create a chair, wee have an instance.
In most languages the new operator is the way to create the instance...
Chair c = new Chair();
There are other ways.
In this case Chair is the object and c is the instance. We can easily create additional chairs as well which has no effect on the object definition.
an instance is a specific realization of an object.
when a application run ,in fact an instance of that program run
for example if we have an object for car , a bmw can be an instance of that
The class file source code defines the object. To use the object in other code you create an instance of it:
Object definition:
public class Person {
String mName;
public Person(){}
public Person(String name){
mName=name;
}
public void setName(String name){
mName=name;
}
public String getName(){
return mName;
}
}
Object use (instances):
Person me=new Person("John Doe");
//me is an instance of the person object;
Person you=new Person("John Smith");
Person spouse=new Person("Jane Doe");
//lots of instances but only one Person Object
String myName=me.getName();
Next read up on static objects :)
I've been hearing these two words used in Microsoft tutorials for VB.NET. What is the difference between these two words when used in reference to variables?
Value vis-a-vis Reference Types
Variables in C# are in 1 of 2 groups. Value types or Reference types. Types like int and DateTime are value types. In contrast, any class you create is a reference type. C# strings are also a reference type. Most things in the .NET framework are reference types.
Parts of a Variable
There is the variable name and its value. Two parts.
The variable's name is what you declare it to be. The value is what you assign to it.
Variables are Initialized
All variables are always given an initial value at the point the variable is declared. Thus all variables are initialized.
For value types, like int the compiler will give them a valid value if you do not do so explicitly. int's initialize to zero by default, DateTime's initialize to DateTime.MinValue by default.
Reference type variables initialize to the object you give it. The compiler will not assign an object (i.e. a valid value) if you don't. In this case the value is null - nothing. So we say that the reference is initialized to null.
Objects are Instantiated
Humans are born. Objects are instantiated. A baby is an instance of a Human, an object is an instance of some Class.
The act of creating an instance of a Class is called instantiation (Ta-Da!)
So declare, initialize, and instantiate come together like this
MyClass myClassyReference = new MyClass();
In the above, it is wrong to say "... creating an instance of an object..."
edit - inspired by comments discussion
Three distinct things are going on (above) using distinct terminology and that terminology is not interchangeable :
A reference variable is declared - MyClass myClassyReference
An object is instantiated (...from/of a given class, implied) - new MyClass()
The object is assigned to the variable. =.
Restating the facts:
A reference-type variable is also called simply "a reference". A "value-type variable" is not a reference.
This: "objectA is an instance of an object" is profoundly wrong. If objectA was "an instance of objectB" then it must be that objectA begins life with objectB's type - whatever that is - and current state - whatever that is. What about creating objects D, E, and F as objectB changes? Nay, nay! It is the conceptual and technical case the "objectA is an instance of a Class". "Instantiation" and "instance of" have precise meaning - an object gets its type, definitions, and values from a Class.
MyClass myClassyReference = null Generally we don't say "the variable is assigned to null" and we never say "the variable is referencing null", No. instead we say "the variable is null"; or "the variable is not referencing anything", or "the reference is null"
Practical Application:
I jab my finger at your code and say "this instance has an invalid property. Maybe that's why the loop fails. You gotta validate parameters during instantiation." (i.e. constructor arguments).
I see this in your code ,
MyClass myClassyReference;
myClassyReference.DoSomething();
"You declared the variable but never assigned it. it's null so it's not referencing anything. That's why the method call throws an exception."
end edit
The Unbearable Lightness of Being
A reference type variable's name and value exists independently. And I do mean independent.
An instantiated object may or may not have a reference to it.
An instantiated object may have many references to it.
A declared reference may or may not be pointing to an object.
A variable is initialized with a value. An object is instantiated when memory is allocated for it and it's constructor has been run.
For instance here is a variable:
Dim obj as Object
This variable has not been initialized. Once I assign a value to the obj variable, the variable will be initialized. Here are examples of initialization:
obj = 1
obj = "foo"
Instantiation is a very different thing but is related since instantiation is usually followed by initialization:
Dim obj As New Object()
In the preceding line of code, the obj variable is initialized with the reference to the new Object that was instantiated. We say that the new Object was instantiated because we have created a new instance of it.
Now I believe that VB.NET makes this a lot more confusing than C# because it is not clear that an assignment is taking place in the code above. In C# it is much clearer that there is both an instantiation of an instance and an initialization of a variable:
Object obj = new Object();
To initialize something is to set it to its initial value. To instantiate something is to create an instance of it.
Often this is the more or less same thing. This:
SqlConnection conn = new SqlConnection();
instantiates a SqlConnection object, and initializes the conn variable by setting it to the that instance.
Since an object's constructor also sets the object's properties to their default values, it's often correct to say that instantiating an object initializes it. (Misleading, if the object exposes a method that you have to explictly call to initialize it after it's instantiated, as is sometimes the case.)
*Instantiation means to create an instance for a class or object.Initialization means to *initiate the same object or class for any purpose.**
Instantiated means that an instance of the object has been created. Initiated means that that same object has done some initialization.
When you instantiate a class or object, you're creating a new instance of it, or allocating memory to "hold" one. Initializing that object would be the instructions that are performed during instantiation.
Instantiation is when you create an instance of a class. That instance is then an object, and you can set its properties, or call methods on it (tell it to do things).
Initiation is when you set up a set of initial conditions for something. That something might be an object, where you tell it to initiate itself, or just a variable to which you assign a value.
An object might initialise some other things, or even instantiate other objects as part of its initiation.
The difference is that instantiation is creation of a thing that can do stuff; initiation is stuff that gets done.
See the Java docs:
https://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html
"Point originOne = new Point(23, 94);
Declaration: The code set in bold are all variable declarations that associate a variable name with an object type.
Instantiation: The new keyword is a Java operator that creates the object.
Initialization: The new operator is followed by a call to a constructor, which initializes the new object."
We can see it this way. For a line of code below:
var p = new Person();
The above line can be read as following two ways:
The variable p has been initialized as a person class
Person class has been instantiated in variable p
The subject of reference or context matters. When talking in terms of variable, we use the word initialize. When talking in terms of class/type, we use the word instantiate.
Instantiation refers to the allocation of memory to create an instance of a class whereas initialization refers to naming that instance by assigning the variable name to that instance.
Eg: SqlConnection conn = new SqlConnection();
Here new is a keyword which allocates memory for an instance and conn is a variable name assigned for that instance.
Others have explained the difference, so I wont go into detail. But there are cases where instantiation does not properly initialize an object. When you instantiate an object you also initialize it with some data. The class/type will have the initialization logic, whereas the instantiation logic is typically carried out by thenew keyword (basically memory allocation, reference copying etc). But instantiation need not necessarily result in a valid state for objects which is when we can say the object is uninitialzed. Here's a practical example where an object can be instantiated but not initialized (sorry e.g. in C#).
class P { string name = "Ralf"; }
WriteLine(new P().name); // "Ralf";
WriteLine((FormatterServices.GetUninitializedObject(typeof(P)) as P).name); // null
GetUninitializedObject doesn't call the constructor to instantiate object there (but some internal magic).
One could also argue value types are not instantiated but only initialized as it doesn't need new allocation when you do new.. but that's up to one's definition of instantiation.
In object-oriented parlance:
To instantiate means creating an object of some class, which initial state may be undefined.
The class is a blueprint which is used by the program to create objects. Objects created are compliant with the blueprint and can be manipulated by the program. E.g. variables current_client and previous_client can be assigned objects of class Customer. An instance of class X is an object instantiated from class X.
In the code the class is a permanent static description of what an object can do, but the objects themselves are temporary and dynamic. They have an individual state which can be changed (e.g. the Customer name, the associated orders). Instantiation can be done like this:
dim current_client as new Customer (VB)
Customer* current_client = new Customer() (C++)
current_client = Customer() (Python)
new Customer, new Customer() and Customer() are equivalent forms in different languages to trigger the instantiation.
In the end objects are destructed to release memory and other resources required for their existence and working.
To initialize means assigning an initial state to the object before it is used.
This initialization can be part of the instantiation process, in that case values are explicitly assigned to object attributes in the constructor of the object. Alternatively it can be left to the user who can decide whether it is required or not. The latter method allows faster instantiation, but requires the user's code to not read the value of any attribute before this code has explicitly assigned a value to this attribute. E.g. this code:
current_client.count = current_client.count + 1
is not allowed before the attribute count has been set by the user, since it can contain any initial value, including an invalid value which would trigger an execution error.