What is the difference between an Instance and an Object? - oop

What is the difference between an Instance and an Object?
Is there a difference or not?

The Instance and Object are from Object Oriented Programming.
For some programming languages like Java, C++, and Smalltalk, it is important to describe and understand code. In other languages that used in Structured Programming, this concept doesn't exist.
This is a view from Structural Programming. There's no real significant difference that should consume too much of your time. There might be some fancy language that some people might take up a lot of spaces to write about, but at the end of the day, as far as a coder, developer, programmer, architect, is concerned, an instance of a class and an object mean the same thing and can often be used interchangeably. I have never met anyone in my career that would be picky and spend a half-hour trying to point out the differences because there's really none. Time can be better spent on other development efforts.
UPDATE With regards to Swift, this is what Apple who invented Swift prefers :
An instance of a class is traditionally known as an object. However,
Swift classes and structures are much closer in functionality than in
other languages, and much of this chapter describes functionality that
can apply to instances of either a class or a structure type. Because
of this, the more general term instance is used.

Excellent question.
I'll explain it in the simplest way possible:
Say you have 5 apples in your basket. Each of those apples is an object of type Apple, which has some characteristics (i.e. big, round, grows on trees).
In programming terms, you can have a class called Apple, which has variables size:big, shape:round, habitat:grows on trees. To have 5 apples in your basket, you need to instantiate 5 apples. Apple apple1, Apple apple2, Apple apple3 etc....
Alternatively: Objects are the definitions of something, instances are the physical things.
Does this make sense?

Instance: instance means just creating a reference(copy).
object: means when memory location is associated with the object (is a run-time entity of the class) by using the new operator.
In simple words, Instance refers to the copy of the object at a particular time whereas object refers to the memory address of the class.

Object:
It is a generice term basically it is a Software bundle that has state(variables) and behaviour(methods)
Class:
A blue print(template) for an object
instance-it's a unique object thing for example you create a object two times what does that mean is yo have created two instances
Let me give an example
Class student()
{
private string firstName;
public student(string fname)
{
firstName=fname;
}
Public string GetFirstName()
{
return firstName;
}
}
Object example:
Student s1=new student("Martin");
Student s2=new student("Kumar");
The s1,s2 are having object of class Student
Instance:
s1 and s2 are instances of object student
the two are unique.
it can be called as reference also.
basically the s1 and s2 are variables that are assigned an object

Objects and instances are mostly same; but there is a very small difference.
If Car is a class, 3 Cars are 3 different objects. All of these objects are instances. So these 3 cars are objects from instances of the Car class.
But the word "instance" can mean "structure instance" also. But object is only for classes.
All of the objects are instances.
Not all of the instances must be objects. Instances may be "structure instances" or "objects".
I hope this makes the difference clear to you.

Let's say you're building some chairs.
The diagram that shows how to build a chair and put it together corresponds to a software class.
Let's say you build five chairs according to the pattern in that diagram. Likewise, you could construct five software objects according to the pattern in a class.
Each chair has a unique number burned into the bottom of the seat to identify each specific chair. Chair 3 is one instance of a chair pattern. Likewise, memory location 3 can contain one instance of a software pattern.
So, an instance (chair 3) is a single unique, specific manifestation of a chair pattern.

Quick and Simple Answer
Class : a specification, blueprint for an object...
Object : physical presence of the class in memory...
Instance : a unique copy of the object (same structure, different data)...

An object is a construct, something static that has certain features and traits, such as properties and methods, it can be anything (a string, a usercontrol, etc)
An instance is a unique copy of that object that you can use and do things with.
Imagine a product like a computer.
THE xw6400 workstation is an object
YOUR xw6400 workstation, (or YOUR WIFE's xw6400 workstation) is an instance of the xw6400 workstation object

Java is an object-oriented programming language (OOP). This means, that everything in Java, except of the primitive types is an object.
Now, Java objects are similar to real-world objects. For example we can create a car object in Java, which will have properties like current speed and color; and behavior like: accelerate and park.
That's Object.
Instance, on the other side, is a uniquely initialized copy of that object that looks like Car car = new Car().
Check it out to learn more about Java classes and object

Once you instantiate a class (using new), that instantiated thing becomes an object. An object is something that can adhere to encapsulation, polymorphism, abstraction principles of object oriented programming and the real thing a program interacts with to consume the instance members defined in class. Object contains instance members (non-static members).
Thus instance of a class is an object. The word ‘instance’ is used when you are referring to the origin from where it born, it's more clearer if you say ‘instance of a class’ compared to ‘object of a class’ (although the latter can be used to).
Can also read the 'Inner classes' section of this java document on nested classes - https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

I can't believe, except for one guy no one has used the code to explain this, let me give it a shot too!
// Design Class
class HumanClass {
var name:String
init(name:String) {
self.name = name
}
}
var humanClassObject1 = HumanClass(name: "Rehan")
Now the left side i.e: "humanClassObject1" is the object and the right side i.e: HumanClass(name: "Rehan") is the instance of this object.
var humanClassObject2 = HumanClass(name: "Ahmad") // again object on left and it's instance on the right.
So basically, instance contains the specific values for that object and objects contains the memory location (at run-time).
Remember the famous statement "object reference not set to an instance of an object", this means that non-initialised objects don't have any instance.
In some programming languages like swift the compiler will not allow you to even design a class that don't have any way to initialise all it's members (variable eg: name, age e.t.c), but in some language you are allowed to do this:
// Design Class
class HumanClass {
var name:String // See we don't have any way to initialise name property.
}
And the error will only be shown at run time when you try to do something like this:
var myClass = HumanClass()
print(myClass.name) // will give, object reference not set to an instance of the object.
This error indicates that, the specific values (for variables\property) is the "INSTANCE" as i tried to explain this above!
And the object i.e: "myClass" contains the memory location (at run-time).

This answer may be seen as trite, but worrying about the differences between an instance and object is already trite city.
I think its best depicted in javascript:
let obj= {"poo":1}
// "obj" is an object
verses
Class Trash {
constructor(){this.poo = 1;}
}
let i = new Trash();
// "i" is an instance

When a variable is declared of a custom type (class), only a reference is created, which is called an object. At this stage, no memory is allocated to this object. It acts just as a pointer (to the location where the object will be stored in future). This process is called 'Declaration'.
Employee e; // e is an object
On the other hand, when a variable of custom type is declared using the new operator, which allocates memory in heap to this object and returns the reference to the allocated memory. This object which is now termed as instance. This process is called 'Instantiation'.
Employee e = new Employee(); // e is an instance
However, in some languages such as Java, an object is equivalent to an instance, as evident from the line written in Oracle's documentation on Java:
Note: The phrase "instantiating a class" means the same thing as "creating an object." When you create an object, you are creating an "instance" of a class, therefore "instantiating" a class.

An instance is a specific representation of an object. An object is a generic thing while an instance is a single object that has been created in memory. Usually an instance will have values assigned to it's properties that differentiates it from other instances of the type of object.

If we see the Definition of Object and Instance object -
Memory allocated for the member of class at run time is called object or object is the instance of Class.
Let us see the Definition of instance -
Memory allocated For Any at run time is called as instance variable.
Now understand the meaning of any run time memory allocation happen in C also through Malloc, Calloc, Realloc such:
struct p
{
}
p *t1
t1=(p) malloc(sizeof(p))
So here also we are allocating run time memory allocation but here we call as instance so t1 is instance here we can not say t1 as object so Every object is the instance of Class but every Instance is not Object.

Object - An instance of a class that has its own state and access to all of the behaviour defined by its class.
Instance - Reference to an memory area for that particular class.

Class : A class is a blue print.
Object : It is the copy of the class.
Instance : Its a variable which is used to hold memory address of the object.
A very basic analytical example
Class House --> Blueprint of the house. But you can't live in the blue print. You need a physical House which is the instance of the class to live in. i.e., actual address of the object is instance. Instances represent objects.

There are 3 things you need to understand : Class , Object and Instance.
Class : Class is the blueprint code from which you will create an Object(s)
Object : When memory is allocated to the data entity (created from blueprint class) , that data entity or reference to it is called Object
Instance : When data is filled in an Object , it becomes an instance of that Object. It can also be called a state of that Object.
Example : In context with C# (objects are reference type here)
Lets say we have a class like this (This is your blueprint code)
public class Animal
{
//some fields and methods
}
We create an object like this
Animal a = new Animal();
Animal b = a;
Animal c = a;
Animal d = b;
So here is the question : How many objects and instances are here ?
Answer : There is only 1 object but 4 instances.
Why ?
In first line (Animal a = new Animal();),we created an Object from class Animal with new Operator. That Object is somewhere on your RAM. And the reference to that Object is in "a".
We have 1 object and 1 instance at this time.
Now in next line, we assign b with a. Here Object is not copied but the reference of object from "a" is stored in "b" too. Thus , we have 2 instances , "a and b".
This goes on and we only copy reference of same object located at some memory.
Finally , we have 4 instances "a,b,c,d" of a single object that was created with new Operator.
(Read how reference type works in C# for more. I hope you understand my language)

each object said to be an instance of its class but each instance of the class has its own value for each attributes
intances shares the attribute name and operation with their intances of class but an object contains an implicit reference to his on class

I can't believe this could be hard to be explain but it actually easier than all the answers I read. It just simple like this.
Firstly, you need understand the definition:
Instance is a **unique copy-product of an Object.
**unique - have different characteristic but share the same class compare to object
Object is a name that been used to keep the Class information (i.e
method)
Let say, there is an toy_1 as an object.
There is also toy_2 as an object ----> which ALSO an INSTANCE to toy_1.
At the same time, toy_1 also an INSTANCE to toy_2. (remember again INSTANCE is a COPY-PRODUCT)
That is why most of the answer I found said it is INTERCHANGABLE. Thank you.

I think if we consider other approaches than OOP (mainly by assuming the term Class hasn't always been used, as it's the case for many C projects, which still applied the concept of Objects), following definitions would make the most sense:
A Class defines an interface that objects adhere to.
An Object is an aggregate of different fields. (It doesn't have to "physically" exist, but it can).
All Objects of the same Class can be used in the same way, defined by the Class.
An Instance is a unique realization of an Object.
As many OOP languages use static typing, the Object description is usually part of the Class already. As such, when talking about an Object in C/C++, what usually is meant is the Instance of an Object.
In languages that do not have static typing (such as JavaScript), Objects can have different fields, while still sharing the same Class.

Regarding the difference between an object and an instance, I do not think there is any consensus.
It looks to me like people change it pretty much interchangeably, in papers, blog posts, books or conversations.
As for me, the way I see it is, an object is a generic and alive entity in the memory, specified by the language it is used in. Just like the Object class in Java. We do not much care its type, or anything else associated with it, whether it is managed by a container or not.
An instance is an object but associated with a type, as in this method accepts Foo instances, or you can not put Animal instances in an instance of
a List of Vehicles.
objects for example have locks associated with them, not instances, whereas instances have methods. objects are garbage collected, not instances.
But as I said, this is only how I see it, and I do not think there is any organisation we can refer to for a standard definition between them and everyone will pretty much have their slightly different understanding / definitions (of course within limits).

An object is a generic thing, for example, take a linear function in maths
ax+b is an object, While 3x+2 is an instance of that object
Object<<< Instance
General<<< Specific
There is nothing more to this

An object can be a class, say you have a class called basketball.
but you want to have multiple basketballs so in your code you create more than 1 basketball
say basketball1 and basketball2.
Then you run your application.
You now have 2 instances of the object basketball.

Object refers to class and instance refers to an object.In other words instance is a copy of an object with particular values in it.

Related

Smalltallk - How can I get an Array (or Collection) of the all the Instance variables in an Object (the current Instance) of a Class?

Let's say we have a Class and we instantiate it, creating an Instance of that Class. This Instance has a number of (instance)variables, defined by the class, that I need to use. I'd like to get all these (instance)variables in an Array or some Collection so I can iterate through them and set them to some value, not nil.
How can I do this?
I would like to build up on #Uko's answer because there is a more direct way to implement his idea.
The message instSize sent to a Class will answer the number of named instance variables of its instances. This, of course, would include instance variables defined in superclasses.
For instance, RemoteTempVectorNode instSize answers with 17 (wow!). Therefore you could do:
fields := (1 to: anObject class instSize) collect: [:i | anObject instVarAt: i]
and then, change them with:
values withIndexDo: [:v :i | anObject instVarAt: i put: v]
where values is the array of new values you want to inject into the object.
So, why I'm suggesting this instead of instVarNamed:? Because the latter is indirect. If you take a look at its implementation you will see that it has to first find out the name of the i-th ivar by sending instVarIndexFor:ifAbsent: to the object's class. In other words, if you need the ivar names, follow #Uko's suggestion; otherwise don't bring them into the equation because they will only add CPU cycles to your program.
One more thing. As #Sean DeNegris wisely raised in his comment to your question, it would be beneficial if you elaborated a little bit more on why you need such an unusual maneuver.
EDIT:
Now that Pharo has Flexible Object Layouts the mapping between inst var names and the class instSize is no longer valid (in classes that use the new capability.) So, the simpler approach of using just indexes would not work with generality. In fact, under the new "taxonomy" the instSize (number of fields) of an object may be different from the #numberOfInstanceVariables. I guess that the added flexibility has its costs and benefits.
You can send #allInstVarNames to a class (Behavior) to get names of all instance variables defined by it and by superclasses. If you need without superclass variables, you can use #instVarNames
Let's say that var is your variable that you need to work with. Then you can get the collection of instance variable names and iterate them.
You can use #instVarNamed:put: to set instance variable by name, and #instVarNamed: to get the value by name (in case you need).
I think that something like this may help you:
var class allInstVarNames do: [ :instVarName |
var instVarNamed: instVarName put: <yourValue>

OOP , object concept

According to the standard definition, an object is an entity that contains both data and behaviour.
According to my understanding the data is sent from outside.For eg,we have a class that computes the square of a number.We create an instance and sends a message,along with the number, to the object to compute the square,.
Are we not sending the data from outside?
Why do all the definitions state that the object contains the data?
Thanks
Data, in this context, is state of the object. The definition says that the state/data of object should be internally stored. For example, consider the following class:
class Math {
Double square(double x) {
return x * x;
}
// other similar functions
}
As a language construct, it is a class. But, it is not a true class in object-oriented sense. Because it does not have a state or data. It is just a function wrapped in a class construct. This is not necessarily wrong. Because in this case, it happens that you have operations that don't need a state.
What the definition trying to emphasize is that: you have a real object, when it (or it's class) has both data and behavior. Not every usage of the class construct represents a true object.
Therefore, you have an object if the class representing it satisfies the following three conditions.
The class has state/date. If not, then it is just a bunch of functions. It is not object-oriented, it is procedural.
The class has behavior. If not, then it is just a container, a bunch of variable ( Structures in C).
Not only the class has state/data and behavior/methods, but there is an intrinsic relation between the data and behavior. Which means that just throwing some variables and functions together does not make a true object. For example, if you have state/data and you also have some method, in the class, but if that function does not need to operate upon any of the state, then there is a question whether that method really belongs to that class.
Below is a simple example of what I think is a proper class (representation of object).
Class Patient {
// blood pressure
double systolic;
double diastolic;
double weight;
int age;
public Patient(double systolic, double diastolic, double weight, int age){
}
Public boolean isHealthy(){
// do some calculations and algorithms on age, weight and blood pressure indicators.
// return result as true of false
}
}
Here, we see that class has both state and behavior. We also see that both state and behavior really belong to this class. They are properties of the concept of patient. We further see that operation has an intrinsic relation to data. You can’t decide whether the patient is healthy or not, without consulting/using its state.
I think the problem is with your example which badly fit with an Object Oriented design. I just mean that computing the square of a number is a memoryless function thus there is obviously no reason to store data inside the object properties. However when you will have to deal with the management of stateful entities you will get more easily the importance of classes and object orientation in general.
Your example is a private case where the object doesn't need to hold data (i.e. state). In this case it can be replaced with a function (just the behavior). Most objects need to store data. E.g., an object Person should contain the qualities describing the person, not just possible behavior.
An object is an instance of a class.
Class (a, a*a) is square class but (2, 4) is an instance of it (object). Yes, data is sent to the class and creates new object.

Difference between object and instance

I know this sort of question has been asked before, but I still feel that the answer is too ambiguous for me (and, by extension, some/most beginners) to grasp.
I have been trying to teach myself broader concepts of programming than procedural and basic OOP. I understand the concrete concepts of OOP (you make a class that has data (members) and functions (methods) and then instantiate that class at run time to actually do stuff, that kind of thing).
I think I have a handle on what a class is (sort of a design blueprint for an instance to be created in its likeness at compile time). But if that's the case, what is an object? I also know that in prototype based languages, this can muck things up even more, but perhaps this is why there needs to be a clear distinction between object and instance in my mind.
Beyond that, I struggle with the concepts of "object" and "instance". A lot of resources that I read (including answers at SO) say that they are largely the same and that the difference is in semantics. Other people say that there is a true conceptual difference between the two.
Can the experts here at SO help a beginner have that "aha" moment to move forward in the world of OOP?
Note: this isn't homework, I don't go to school - however, I think it would help people that are looking for homework help.
A blueprint for a house design is like a class description. All the houses built from that blueprint are objects of that class. A given house is an instance.
The truth is that object oriented programming often creates confusion by creating a disconnect between the philosophical side of development and the actual mechanical workings of the computer. I'll try to contrast the two for you:
The basic concept of OOP is this: Class >> Object >> Instance.
The class = the blue print.
The Object is an actual thing that is built based on the 'blue print' (like the house).
An instance is a virtual copy (but not a real copy) of the object.
The more technical explanation of an 'instance' is that it is a 'memory reference' or a reference variable. This means that an 'instance' is a variable in memory that only has a memory address of an object in it. The object it addresses is the same object the instance is said to be 'an instance of'. If you have many instances of an object, you really just have many variables in difference places in your memory that all have the same exact memory address in it - which are all the address of the same exact object. You can't ever 'change' an instance, although it looks like you can in your code. What you really do when you 'change' an instance is you change the original object directly. Electronically, the processor goes through one extra place in memory (the reference variable/instance) before it changes the data of the original object.
The process is: processor >> memory location of instance >> memory location of original object.
Note that it doesn't matter which instance you use - the end result will always be the same. ALL the instances will continue to maintain the same exact information in their memory locations - the object's memory address - and only the object will change.
The relationship between class and object is a bit more confusing, although philosophically its the easiest to understand (blue print >> house). If the object is actual data that is held somewhere in memory, what is 'class'? It turns out that mechanically the object is an exact copy of the class. So the class is just another variable somewhere else in memory that holds the same exact information that the object does. Note the difference between the relationships:
Object is a copy of the class.
Instance is a variable that holds the memory address of the object.
You can also have multiple objects of the same class and then multiple instances of each of those objects. In these cases, each object's set of instances are equivalent in value, but the instances between objects are not. For example:
Let Class A
From Class A let Object1, Object2, and Object3.
//Object1 has the same exact value as object2 and object3, but are in different places in memory.
from Object1>> let obj1_Instance1, obj1_Instace2 , obj1_Instance3
//all of these instances are also equivalent in value and in different places in memory. Their values = Object1.MemoryAddress.
etc.
Things get messier when you start introducing types. Here's an example using types from c#:
//assume class Person exists
Person john = new Person();
Actually, this code is easier to analyze if you break it down into two parts:
Person john;
john = new Person();
In technical speak, the first line 'declares a variable of type Person. But what does that mean?? The general explanation is that I now have an empty variable that can only hold a Person object. But wait a minute - its an empty variable! There is nothing in that variables memory location. It turns out that 'types' are mechanically meaningless. Types were originally invented as a way to manage data and nothing else. Even when you declare primitive types such as int, str, chr (w/o initializing it), nothing happens within the computer. This weird syntactical aspect of programming is part of where people get the idea that classes are the blueprint of objects. OOP's have gotten even more confusing with types with delegate types, event handlers, etc. I would try not focus on them too much and just remember that they are all a misnomer. Nothing changes with the variable until its either becomes an object or is set to a memory address of an object.
The second line is also a bit confusing because it does two things at once:
The right side "new Person()" is evaluated first. It creates a new copy of the Person class - that is, it creates a new object.
The left side "john =", is then evaluated after that. It turns john into a reference variable giving it the memory address of the object that was just created on the right side of the same line.
If you want to become a good developer, its important to understand that no computer environment ever works based on philosophic ideals. Computers aren't even that logical - they're really just a big collection of wires that are glued together using basic boolean circuits (mostly NAND and OR).
The word Class comes from Classification (A Category into which something is put), Now we have all heard that a Class is like a Blueprint,but what does this exactly mean ? It means that the Class holds a Description of a particular Category ,(I would like to show the difference between Class , Object and Instance with example using Java and I would request the readers to visualise it like a Story while reading it , and if you are not familiar with java doesn't matter) So let us start with make a Category called HumanBeing , so the Java program will expressed it as follows
class HumanBeing{
/*We will slowly build this category*/
}
Now what attributes does a HumanBeing have in general Name,Age,Height,Weight for now let us limit our self to these four attributes, let us add it to our Category
class HumanBeing{
private String Name;
private int Age;
private float Height;
private float Weight;
/*We still need to add methods*/
}
Now every category has a behaviour for example category Dog has a behaviour to bark,fetch,roll etc... , Similarly our category HumanBeing can also have certain behaviour,for example when we ask our HumanBeing what is your name/age/weight/height? It should give us its name/age/weight/height, so in java we do it as follows
class HumanBeing{
private String Name;
private int Age;
private float Height;
private float Weight;
public HumanBeing(String Name,int Age,float Height,float Weight){
this.Name = Name;
this.Age = Age;
this.Height = Height;
this.Weight = Weight;
}
public String getName(){
return this.Name;
}
public int getAge(){
return this.age;
}
public float getHeight(){
return this.Height;
}
public float getWeight(){
return this.Weight;
}
}
Now we have added behaviour to our category HumanBeing,so we can ask for its name ,age ,height ,weight but whom will you ask these details from , because class HumanBeing is just a category , it is a blueprint for example an Architect makes a blueprint on a paper of the building he wants to build , now we cannot go on live in the blueprint(its description of the building) we can only live in the building once it is built
So here we need to make a humanbeing from our category which we have described above , so how do we do that in Java
class Birth{
public static void main(String [] args){
HumanBeing firstHuman = new HumanBeing("Adam",25,6.2,90);
}
}
Now in the above example we have created our first human being with name age height weight , so what exactly is happening in the above code? . We are Instantiating our category HumanBeing i.e An Object of our class is created
Note : Object and Instance are not Synonyms In some cases it seems like Object and Instance are Synonyms but they are not, I will give both cases
Case 1: Object and Instance seems to be Synonyms
Let me elaborate a bit , when we say HumanBeing firstHuman = new HumanBeing("Adam",25,6.2,90); An Object of our category is created on the heap memory and some address is allocated to it , and firstHuman holds a reference to that address, now this Object is An Object of HumanBeing and also An Instance of HumanBeing.
Here it seems like Objects and Instance are Synonyms,I will repeat myself they are not synonyms
Let Us Resume our Story , we have created our firstHuman , now we can ask his name,age,height,weight , this is how we do it in Java
class Birth{
public static void main(String [] args){
HumanBeing firstHuman = new HumanBeing("Adam",25,6.2,90);
System.out.println(firstHuman.getName());
System.out.println(firstHuman.getAge());
...
...
}
}
so we have first human being and lets move feather by give our first human being some qualification ,let's make him a Doctor , so we need a category called Doctor and give our Doctor some behaviour ,so in java we do as follows
class Doctor extends HumanBeing{
public Doctor(String Name,int Age,float Height,float Weight){
super(Name,Age,Height,Weight);
}
public void doOperation(){
/* Do some Operation*/
}
public void doConsultation(){
/* Do so Consultation*/
}
}
Here we have used the concept of Inheritance which is bringing some reusability in the code , Every Doctor will always be a HumanBeing first , so A Doctor will have Name,Age,Weight,Height which will be Inherited from HumanBeing instead of writing it again , note that we have just written a description of a doctor we have not yet created one , so let us create a Doctor in our class Birth
class Birth{
public static void main(String [] args){
Doctor firstDoctor = new Doctor("Strange",40,6,80);
.......
.......
/*Assume some method calls , use of behaviour*/
.......
.......
}
}
Case 2: Object and Instance are not Synonyms
In the above code we can visualise that we are Instantiating our category Doctor and bringing it to life i.e we are simply creating an Object of the category Doctor , As we already know Object are created on Heap Memory and firstDoctor holds a reference to that Object on the heap ;
This particular Object firstDoctor is as follows (please note firstDoctor holds a reference to the object , it is not the object itself)
firstDoctor is An Object of class Doctor And An Instance of A class Doctor
firstDoctor is Not An Object of class HumanBeing But An Instance of class HumanBeing
So a particular Object can be an instance to a particular class but it need not be an object of that given class
Conclusion:
An Object is said to be an Instance of a particular Category if it satisfies all the characteristic of that particular Category
Real world example will be as follows , we are first born as Humans so image us as Object of Human , now when we grow up we take up responsibilities and learn new skills and play different roles in life example Son, brother, a daughter, father ,mother now What are we actually?We can say that we are Objects of Human But Instances of Brother,daughter,...,etc
I hope this helps
Thank You
Objects are things in memory while instances are things that reference to them. In the above pic:
std(instance) -> Student Object (right)
std1(instance) -> Student Object (left)
std2(instance) -> Student Object (left)
std3(instance) -> no object (null)
An object is an instance of a class (for class based languages).
I think this is the simplest explanation I can come up with.
A class defines an object. You can go even further in many languages and say an interface defines common attributes and methods between objects.
An object is something that can represent something in the real world. When you want the object to actually represent something in the real world that object must be instantiated. Instantiation means you must define the characteristics (attributes) of this specific object, usually through a constructor.
Once you have defined these characteristics you now have an instance of an object.
Hope this clears things up.
"A class describes a set of objects called its instances." - The Xerox learning Research Group, "The Smalltalk-80 System", Byte Magazine Volume 06 Number 08, p39, 1981.
What is an Object ?
An object is an instance of a class. Object can best be understood by finding real world examples around you. You desk, your laptop, your car all are good real world examples of an object.
Real world object share two characteristics, they all have state and behaviour. Humans are also a good example of an object, We humans have state/attributes - name, height, weight and behavior - walk, run, talk, sleep, code :P.
What is a Class ?
A class is a blueprint or a template that describes the details of an object. These details are viz
name
attributes/state
operations/methods
class Car
{
int speed = 0;
int gear = 1;
void changeGear(int newGear)
{
gear = newGear;
}
void speedUp(int increment)
{
speed = speed + increment;
}
void applyBrakes(int decrement)
{
speed = speed - decrement;
}
}
Consider the above example, the fields speed and gear will represent the state of the object, and methods changeGear, speedUp and applyBrakes define the behaviour of the Car object with the outside world.
References:
What is an Object ?
What is a Class ?
I think that it is important to point out that there are generally two things. The blueprint and the copies. People tend to name these different things; classes, objects, instances are just some of the names that people use for them. The important thing is that there is the blueprint and copies of it - regardless of the names for them. If you already have the understanding for these two, just avoid the other things that are confusing you.
Lets compare apples to apples. We all know what an apple is. What it looks like. What it tastes like. That is a class. It is the definition of a thing. It is what we know about a thing.
Now go find an apple. That is an instance. We can see it. We can taste it. We can do things with it. It is what we have.
Class = What we know about something. A definition.
Object/Instance = Something that fits that definition that we have and can do things with.
In some cases, the term "object" may be used to describe an instance, but in other cases it's used to describe a reference to an instance. The term "instance" only refers to the actual instance.
For example, a List may be described as a collection of objects, but what it actually holds are references to object instances.
I have always liked the idea that equals the definition of a class as that of an "Abstract Data Type". That is, when you defined a class you're are defining a new type of "something", his data type representation, in terms of primitives and other "somethings", and his behavior in terms of functions and/or methods. (Sorry for the generality and formalism)
Whenever you defined a class you open a new possibility for defining certain entities with its properties and behavior, when you instantiate and/or create a particular object out of it you're actually materializing that possibility.
Sometimes the terms object and instances are interchangeable. Some OOP purists will maintain that everything is an object, I will not complain, but in the real OOP world, we developers use two concepts:
Class: Abstract Data Type sample from which you can derive other ADT and create objects.
Objects: Also called instances, represents particular examples of the data structures and functions represented by a given Abstract Data Type.
Object Oriented Programming is a system metaphor that helps you organize the knowledge your program needs to handle, in a way that will make it easier for you to develop your program. When you choose to program using OOP you pick up your OOP-Googles, and you decide that you will see the problem of the real world as many objects collaborating between themselves, by sending messages. Instead of seeing a Guy driving a Car you see a Guy sending a message to the car indicating what he wants the car to do. The car is a big object, and will respond to that message by sending a message to it's engine or it's wheel to be able to respond properly to what the Driver told him to do in the message, etc...
After you've created your system metaphor, and you are seeing all the reality as objects sending messages, you decide to put all the things your are seeing that are relevant to your problem domain in the PC. There you notice that there are a lot of Guys driving different cards, and it's senseless to program the behavior of each one of them separately because they all behave in the same way... So you can say two things:
All those guys behave in the same way, so I'll create a class called
Driver that will specify who all the Drivers in the world behave,
because they all behave in the same way. (And your are using class based OOP)
Or your could say Hey! The second Driver behaves in the same way as the first Driver, except he likes going a little faster. And the third Driver behaves in the same way as the first Driver, except he likes zigzagging when he drives. (And you use prototype based OOP).
Then you start putting in the computer the information of how all the Drivers behave (or how the first driver behave, and how the second and third differ from that one), and after a while you have your program, and you use the code to create three drivers that are the model you are using inside that PC to refeer to the drivers you saw in the real world. Those 3 drivers that you created inside the PC are instances of either the prototype ( actually the first one is the prototype, the first one might be the prototype himself depending on how you model things) or the class that you created.
The difference between instance and object is that object is the metaphor you use in the real world. You choose to see the guy and the car as objects (It would be incorrect to say that you see them as instances) collaborating between themselves. And then you use it as inspiration to create your code. The instance only exists in your program, after you've created the prototype or the class. The "objects" exist outside the PC because its the mapping you use to unite the real world with the program. It unites the Guy with the instance of Driver you created in the PC. So object and instance are extremely related, but they are not exactly the same (an instance is a "leg" of an object in the program, and the other "leg" is in the real world).
I guess the best answer has already been given away.
Classes are blueprints, and objects are buildings or examples of that blueprint did the trick for me as well.
Sometimes, I'd like to think that classes are templates (like in MS Word), while objects are the documents that use the template.
Extending one of the earlier given examples in this thread...
Consider a scenario - There is a requirement that 5 houses need to be built in a neighbourhood for residential purposes. All 5 houses share a common construction architecture.
The construction architecture is a class.
House is an object.
Each house with people staying in it is an instance.

What is an instance of a field called?

This might be an odd question, but it has actually caused me some headache.
In Object oriented programming, there are accepted names for key concepts. In our model, we have classes with methods and fields. Now, going to the data world:
An instance of a class is called an object.
An instance of a field is called... what?
A value? Isn't the term value a little broad for this? I have been offered "property" as well, but isn't property also part of the model and not the data?
(This is not purely academic, I am actually coding these concepts.)
Updated: Let me take an example. I have a class "Person" with a field "age". If I create 20 Person instances, each such instance is called an object. So far so good. But let's say I take Person "Igor", and set his age to 20. What is the storage location that contains the number 20 now called? Is it a field, or a value, or something else?
Another update: A quote from Pavel Feldman in this related question describes in different words what I tried to describe above:
"I'd say that in class-based OOP field belongs to class and does not have a value. It is so when you look at reflection in c# or java - class has fields, field has type, name, etc. And you can get value of the field from object. You declare field once, in class. You have many objects with same fields but different values."
A field can't be instantiated. A field can only contain a value. The value can be either a primitive/native type or a reference/pointer to an object instance.
As per your update: if the object represents a real world entitiy, then it's often called property. With a "real world entity" I mean something personal/human, e.g. Person, Product, Order, Car, etc. If the object does not represent something personal/human, e.g. List, String, Map, then it's more often called field. That's just what I've observed as far.
Agree with BalusC. However I think what you are asking is what to call the field of an instantiated object. Remember that an object contains both state (data) and operations (methods) you could refer to an object field as state
A field is a field weather you talk about it in the context of a class, or in the context of an object.
class C {
int i; // i is a field
}
and
obj = new C();
obj.i = 7; // obj.i is a field
As opposed to parameter vs argument there is no distinction in terminology for "instantiated" an "uninstantiated" fields.
An instance of a class is an object, a class may contain fields that point to other instantiated objects (or a null pointer). It makes no sense to say an instance of a field, but rather you might talk about the object to which a particular field points to, which may be different for different instances. Or you may talk about the type of a field (which class it belongs to)
Isn't the answer basically that we have no name for values of fields of an instance of a class (or object)?
It's like giving a name to the value returned by a method of an instance of a class...
I guess "state" is the best answer anyway as suggested "BalusC".

What is the difference between Composition and Association relationship?

In OOP, what is the difference between composition (denoted by filled diamond in UML) and association (denoted by empty diamond in UML) relationship between classes. I'm a bit confused. What is aggregation? Can I have a convincing real world example?
COMPOSITION
Imagine a software firm that is composed of different Business Units (or departments) like Storage BU, Networking BU. Automobile BU. The life time of these Business Units is governed by the lifetime of the organization. In other words, these Business Units cannot exist independently without the firm. This is COMPOSITION. (ie the firm is COMPOSED OF business units)
ASSOCIATION
The software firm may have external caterers serving food to the employees. These caterers are NOT PART OF the firm. However, they are ASSOCIATED with the firm. The caterers can exist even if our software firm is closed down. They may serve another firm! Thus the lifetime of caterers is not governed by the lifetime of the software firm. This is typical ASSOCIATION
AGGREGATION
Consider a Car manufacturing unit. We can think of Car as a whole entity and Car Wheel as part of the Car. (at this point, it may look like composition..hold on) The wheel can be created weeks ahead of time, and it can sit in a warehouse before being placed on a car during assembly. In this example, the Wheel class's instance clearly lives independently of the Car class's instance.
Thus, unlike composition, in aggregation, life cycles of the objects involved are not tightly coupled.
Here go a few examples:
I am an employee of a company, hence I am associated to that company. I am not part of it, nor do I compose it, but am related to it, however.
I am composed of organs, which unless are transplanted, will die with me. This is composition, which is a very strong bind between objects. Basically objects are composed by other objects. The verb says everything.
There is also another less bound kind of composition, called aggregation. An aggregation is when objects are composed by other objects, but their life cycles are not necessarily tied. Using an extreme example, a Lego toy is an aggregation of parts. Even though the toy can be dismantled, its parts can be recombined to make a different toy.
Owning and using.
Composition: the object with the reference owns the object referred to, and is responsible for its "lifetime", its destruction (and often creation, though it may be passed in). Also known as a has-a relationship.
Association: the object with the reference uses the object referred to, may not be an exclusive user, and isn't responsible for he referred-to object's lifetime. Also known as a uses-a relationship.
The OP comments:
Can you provide a real world example. Also, what is aggregation? – Marc
Aggregation: an Association that is from whole to part, and that can't be cyclic.
Examples:
Composition: a Car has-an Engine, a Person has-an Address. Basically, must have, controls lifetime.
Association: A Car has-a Driver, some class instance has-an ErrorLogger. Lifetime not controlled, may be shared.
Aggregation: A DOM (Document Object Model, that is the objects that make up a tree of HTML elements) Node has-a (an array of) child Nodes. The Node is top (well, higher) level; it "contains" its children, they don't contain it.
I believe that a code-based example can help to illustrate the concepts given by the above responses.
import java.util.ArrayList;
public final class AssoCia
{
public static void main( String args[] )
{
B b = new B();
ArrayList<C> cs = new ArrayList();
A a = new A( b, cs );
a.addC( new C() );
a.addC( new C() );
a.addC( new C() );
a.listC();
}
}
class A
{
// Association -
// this instance has a object of other class
// as a member of the class.
private B b;
// Association/Aggregation -
// this instance has a collection of objects
// of other class and this collection is a
// member of this class
private ArrayList<C> cs;
private D d;
public A(B b, ArrayList<C> cs)
{
// Association
this.b = b;
// Association/Aggregation
this.cs = cs;
// Association/Composition -
// this instance is responsible for creating
// the instance of the object of the
// other class. Therefore, when this instance
// is liberated from the memory, the object of
// the other class is liberated, too.
this.d = new D();
}
// Dependency -
// only this method needs the object
// of the other class.
public void addC( C c )
{
cs.add( c );
}
public void listC()
{
for ( C c : cs )
{
System.out.println( c );
}
}
}
class B {}
class C {}
class D {}
Independent existence.
An Invoice is composed of line items.
What's a line item that's not on an invoice? It's -- well -- it's nothing. It can't exist independently.
On the other hand, an Invoice is associated with a Customer.
Customer has an independent existence, with or without an invoice.
If the two things have independent existence, they may be associated.
If one thing cannot exist independently, then it is part of a composition.
Usually, composition means that the lifetime of the contained object is bounded by that of the container, whereas association is a reference to an object which may exist independently.
However, this is just the practice I've observed. I hate to admit it, but ploughing through the UML2 spec isn't high on my list of fun stuff to do!
Composition is a stricter relationship than aggregation. Composition means that something is so strongly related to something else that they cannot basically exist independently, or if they can, they live in different contexts.
Real world example: you define a GUI window, and then a text field where to write something.
Between the class defining the GUI and the class defining the text field there's composition. Together, they compose a widget which can be seen as an entity on its own. Suppose you delete the window, and you delete the text field as well.
Aggregation is different, in the sense that the link between the two entities is temporary, unstable, and occasional. A real world example. Suppose you have a database of objects containing multiple data instances. Now you run some filter to collect the data instances obeying a given criterium, and the resulting instances are pushed into a graphical list so that the user can see them. When the graphical widget receives the objects, it can form an aggregation of these entities, and present them. If the user closes the window with the graphical list, and the latter get deleted, the data objects should not be deleted. Maybe they are displayed somewhere else, or you still need them.
Also, in general, composition is defined at creation time. Aggregation is instead defined later in the object lifetime.
Composition means a part of the entity state is encapsulated by another type but it is conceptualy part of the entity state. For example you may have a address type and a employee entity type that includes a address.
Association means that a entity type is assocciated with another entity type but the assocciated entity is conceptualy not part of the entity state. For example a employee may be assocciated with a company.