110

What is a class, an object and an instance in Java?

spongebob
  • 8,370
  • 15
  • 50
  • 83
Pranjut
  • 1,747
  • 5
  • 18
  • 31

16 Answers16

118

A class is a blueprint which you use to create objects. An object is an instance of a class - it's a concrete 'thing' that you made using a specific class. So, 'object' and 'instance' are the same thing, but the word 'instance' indicates the relationship of an object to its class.

This is easy to understand if you look at an example. For example, suppose you have a class House. Your own house is an object and is an instance of class House. Your sister's house is another object (another instance of class House).

// Class House describes what a house is
class House {
    // ...
}

// You can use class House to create objects (instances of class House)
House myHouse = new House();
House sistersHouse = new House();

The class House describes the concept of what a house is, and there are specific, concrete houses which are objects and instances of class House.

Note: This is exactly the same in Java as in all object oriented programming languages.

Jesper
  • 202,709
  • 46
  • 318
  • 350
  • `class House {` `// blue print for House Objects` `}` `class Car {` `// blue print for Instances of Class Car ` `}` `House myHouse = House new();` `Car myCar = Car new();` – Suraj Jain Dec 25 '16 at 03:43
  • myHouse and myCar are objects myHouse is an instance of House (relates Object-myHouse to its Class-House) myCar is an instance of Car. Is this true , please see the above answer by user2390183 is it correct or not ? – Suraj Jain Dec 25 '16 at 03:44
  • Is it possible to have an object that is not the instance of a class? Just an object you declare by itself. – Juan Perez May 26 '23 at 22:06
  • @JuanPerez No, all objects are instances of some class. – Jesper May 30 '23 at 08:11
99

Java (and any other programming language) is modeled in terms of types and values. At the theoretical level, a value is a representation for some quantum of information, and a type is a set of values. When we say value X is an instance of type Y, we are simply saying that X is a member of the set of values that is the type Y.

So that's what the term "instance" really means: it describes a relationship not a thing.

The type system of the Java programming language supports two kinds of types, primitive types and reference types. The reference types are further divided into the classes and array types. A Java object is an instance of a reference type.

An object is a class instance or an array. (JLS 4.3.1)

That's the type theoretic view.

In practice, most Java developers treat the words "instance" and "object" as synonyms. (And that includes me then I'm trying to explain something quickly.) And most developers use the word "value" rather than "instance" to refer to an instance of a primitive type.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 3
    I really appreciate your answer sir, and I almost got it, just one more question. We say-"Whenever the compiler hits the 0 argument constructor it creates a instance of a class.". In this context what is really created an instance or an object? An object I guess and we use the word "instance" as synonym.But it would kind, if you better confirm it. – Pranjut Aug 02 '09 at 02:23
  • 3
    @Ryan: Basically yes: it is creating an Object which is an instance of the Class in question. (But note that the quoted sentence is saying "instance of a Class" rather than just "instance" ... so the author is not actually using "instance" as a synonym here.) – Stephen C Aug 02 '09 at 03:38
  • in the context of Java (and _some_ other languages) your theoretical explanation is sound. -however there are language that would contradict your leading statement. Simula the origin of OO would be one but there are other. There exist several languages where types them self are represented by object and thus are values. Eg the type of an object in JS is a value – Rune FS Apr 06 '15 at 19:30
  • 1
    @RuneFS - the "modelling" I am talking about is not about representation. It is theoretical. Yea, in some languages there are objects that denote types, or even that allow you to enumerate all of the instances of a type. But those properties augment the generic "modelling" rather than invalidating it. – Stephen C Apr 06 '15 at 22:50
  • @StephenC well in that case it should be data and operations since modern day computing is build on the von neumann architecture which has no types – Rune FS Apr 07 '15 at 15:12
  • 1
    @RuneFS - No ... I am talking about "type theory". It is a branch of mathematics. It is independent of the technology that is used to run programs. The closest type theory gets to computation is lambda calculus. (If you are interested, try and get hold of a copy of "Types and Programming Languages" by Benjamin C. Pierce.) – Stephen C Apr 07 '15 at 15:32
  • I've never met values in type theory only terms and types but i've met values and types when talking about different paradigms and different type system which is what got me confused. – Rune FS Apr 07 '15 at 18:12
  • Sir , Can You tell me is user2390183 answer below is correct or not , i liked his answer and just want to confirm that i got right or not >? – Suraj Jain Dec 25 '16 at 03:45
  • @SurajJain - It is sort of correct, though there are a couple of things that could be read the wrong way. For example, saying that `myHouse` is an instance is technically incorrect. Actually, `myHouse` is a variable that refers to an instance of `House`. – Stephen C Dec 25 '16 at 09:36
  • So correct me if i am wrong , i understand that class is a definition or a template , a blueprint type of thing , like if i make a class `Human` , I would in that have its elements as `Height` , `weight` and so on , Now if i make an object named `suraj` refer to the class person instance . Similarly i can have a class `house` and `myhouse` refers to the house instance. So `myhouse` and `suraj` are objects , and house and person are classes. But `myhouse` refers to` house` instance and `suraj` refers to `house` instance. – Suraj Jain Dec 25 '16 at 16:02
  • Both are objects, difference is only in the relationship with class , that is the instance. – Suraj Jain Dec 25 '16 at 16:02
  • 1
    You are making the same mistake as `user2390183`. You are treating variables as "names". They are not. Variables are "reference holders" that contain references to objects. Objects don't have intrinsic names. The references are the closest thing that there is to a "name" for an object, except that they don't have a constant representation. (The GC can move an object which changes the bit pattern used to represent the reference.) – Stephen C Dec 25 '16 at 22:33
  • I don't think it makes sense to say that an instance is not a "thing", just because it is an instance *of* something. Obviously `instanceof` is a relation between two things, but it does not make sense to say "X is an instance of Y" if "an instance" is not a *thing* that X can be. Consider: a house is a "thing", even though it is a house *of bricks* or a house *of cards*. – kaya3 Mar 02 '20 at 15:33
  • Your opinion is noted :-) Feel free to vote for someone else's answer .... or write your own. But note that I am not basing my argument on an analogy with other English words. I am basing it on concepts of **type theory**. Admittedly, in a rather clumsy way. – Stephen C Mar 02 '20 at 15:48
31

A class is basically a definition, and contains the object's code. An object is an instance of a class

for example if you say

String word = new String();

the class is the String class, which describes the object (instance) word.

When a class is declared, no memory is allocated so class is just a template.

When the object of the class is declared, memory is allocated.

DevD
  • 55
  • 1
  • 15
mustafabar
  • 2,317
  • 6
  • 31
  • 47
  • Did you mean that objects and instances are same? – Pranjut Aug 01 '09 at 05:20
  • Thanks david for the link. From the topics I got this Every real world things which have state and behaviour can be called as "object". And to classify these objects we use class(A class is the blueprint from which individual objects are created). And it says that, the objects of the class are instances. Now please someone tell me what is the differences between object and instance?Does this mean that object don't really exist in context of programming and instance represents object in it? – Pranjut Aug 01 '09 at 06:13
  • @Mustafa: I'm sorry to contradict you, but according to the JLS, an array is also an object in Java. And you'll find that the JLS does not define the term 'instance' at all. See my answer. – Stephen C Aug 01 '09 at 14:10
  • @Ryan: See my answer for the distinction between "instance" and "object". @Mustafa's answer and comment are (IMO) misleading. – Stephen C Aug 02 '09 at 01:51
  • @mustafabar - *"When a class is declared, no memory is allocated so class is just a template."* - And this isn't true either. Memory is allocated to (at least) represent the `static` variables of the class. (And for other things too that are related to the type identity of the class.) – Stephen C Dec 25 '16 at 11:16
15

I like Jesper's explanation in layman terms

By improvising examples from Jesper's answer,

class House {
// blue print for House Objects
}

class Car {
// blue print for Instances of Class Car 
}

House myHouse = new House();
Car myCar = new Car();

myHouse and myCar are objects

myHouse is an instance of House (relates Object-myHouse to its Class-House) myCar is an instance of Car

in short

"myHouse is an instance of Class House" which is same as saying "myHouse is an Object of type House"

Shreshth Kharbanda
  • 1,777
  • 14
  • 24
user2390183
  • 975
  • 8
  • 17
7

Class is Data Type,You use this type to create object.

  • Instance is Logical but object is Physical means occupies some memory.

  • We can create an instance for abstract class as well as for interface, but we cannot create an
    object for those.

  • Object is instance of class and instance means representative of class i.e object.

  • Instance refers to Reference of an object.

  • Object is actually pointing to memory address of that instance.

  • You can’t pass instance over the layers but you can pass the object over the layers

  • You can’t store an instance but you can store an object

  • A single object can have more than one instance.

  • Instance will have the both class definition and the object definition where as in object it will have only the object definition.

Syntax of Object:

 Classname var=new Classname();

But for instance creation it returns only a pointer refering to an object, syntax is :

 Classname varname;
Lucky
  • 16,787
  • 19
  • 117
  • 151
SwatiKothari
  • 371
  • 3
  • 8
4

Class : Structure

Object : Physical Manifestation

Instance : each object created from class

Reference : Address of Object

kk.
  • 3,747
  • 12
  • 36
  • 67
Abishek M
  • 61
  • 7
  • 1
    Objects in the real world are physical. Objects in a computer program are not physical. (You can't touch them. They don't obey the laws of physics. Etcetera. And even the bit patterns in memory are *representations* of objects ... not actual Java objects.) – Stephen C May 07 '21 at 23:24
3

In java, the objects are spawned on heap memory. These require reference to be pointed and used in our application. The reference has the memory location of the object with which we can use the objects in our application. A reference in short is nothing but a name of the variable which stores the address of the object instantiated on a memory location.

An instance is a general term for object. FYI, Object is a class.

For Example,

Class A{

}

A ref = new A();

For the above code snippet, ref is the reference for an object of class A generated on heap.

Arun
  • 2,562
  • 6
  • 25
  • 43
3

Honestly, I feel more comfortable with Alfred blog definitions:

Object: real world objects shares 2 main characteristics, state and behavior. Human have state (name, age) and behavior (running, sleeping). Car have state (current speed, current gear) and behavior (applying brake, changing gear). Software objects are conceptually similar to real-world objects: they too consist of state and related behavior. An object stores its state in fields and exposes its behavior through methods.

Class: is a “template” / “blueprint” that is used to create objects. Basically, a class will consists of field, static field, method, static method and constructor. Field is used to hold the state of the class (eg: name of Student object). Method is used to represent the behavior of the class (eg: how a Student object going to stand-up). Constructor is used to create a new Instance of the Class.

Instance: An instance is a unique copy of a Class that representing an Object. When a new instance of a class is created, the JVM will allocate a room of memory for that class instance.

Given the next example:

public class Person {
    private int id;
    private String name;
    private int age;

    public Person (int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        return result;
    }

    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (id != other.id)
            return false;
        return true;
    }

    public static void main(String[] args) {
        //case 1
        Person p1 = new Person(1, "Carlos", 20);
        Person p2 = new Person(1, "Carlos", 20);

        //case 2
        Person p3 = new Person(2, "John", 15);
        Person p4 = new Person(3, "Mary", 17);
    }
}

For case 1, there are two instances of the class Person, but both instances represent the same object.

For case 2, there are two instances of the class Person, but each instance represent a different object.

So class, object and instance are different things. Object and instance are not synonyms as is suggested in the answer selected as right answer.

Carlos Casallas
  • 304
  • 3
  • 9
2

If you have a program that models cars you have a class to represent cars, so in Code you could say:

Car someCar = new Car();

someCar is now an instance of the class Car. If the program is used at a repairshop and the someCar represents your car in their system, then your car is the object.

So Car is a class that can represent any real world car someCar is an instance of the Car class and someCare represents one real life object (your car)

however instance and object is very often used interchangably when it comes to discussing coding

Rune FS
  • 21,497
  • 7
  • 62
  • 96
2

Any kind of data your computer stores and processes is in its most basic representation a row of bits. The way those bits are interpreted is done through data types. Data types can be primitive or complex. Primitive data types are - for instance - int or double. They have a specific length and a specific way of being interpreted. In the case of an integer, usually the first bit is used for the sign, the others are used for the value.

Complex data types can be combinations of primitive and other complex data types and are called "Class" in Java.

You can define the complex data type PeopleName consisting of two Strings called first and last name. Each String in Java is another complex data type. Strings in return are (probably) implemented using the primitive data type char for which Java knows how many bits they take to store and how to interpret them.

When you create an instance of a data type, you get an object and your computers reserves some memory for it and remembers its location and the name of that instance. An instance of PeopleName in memory will take up the space of the two String variables plus a bit more for bookkeeping. An integer takes up 32 bits in Java.

Complex data types can have methods assigned to them. Methods can perform actions on their arguments or on the instance of the data type you call this method from. If you have two instances of PeopleName called p1 and p2 and you call a method p1.getFirstName(), it usually returns the first name of the first person but not the second person's.

Kage
  • 395
  • 1
  • 3
  • 9
2

The concept behind classes and objects is to encapsulate logic into single programming unit. Classes are the blueprints of which objects are created.

Here an example of a class representing a Car:

public class Car {

    int currentSpeed;
    String name;

    public void accelerate() {  
    }

    public void park() {
    }

    public void printCurrentSpeed() {
    }
}

You can create instances of the object Car like this:

Car audi = new Car();
Car toyota = new Car();

I have taken the example from this tutorial

filip_j
  • 993
  • 1
  • 14
  • 22
1

Class

  • It has logical existence, i.e. no memory space is allocated when it is created.

  • It is a set of objects.

  • A class may be regarded as a blueprint to create objects.

    • It is created using class keyword

    • A class defines the methods and data members that will be possessed by Objects.


Object

  • It has physical existence, i.e. memory space is allocated when it is created.

  • It is an instance of a class.

  • An object is a unique entity which contains data members and member functions together in OOP language.

    • It is created using new keyword

    • An object specifies the implementations of the methods and the values that will be possessed by the data members in the class.

  • 1
    Space may be allocated when a class is "created". The space is required for any static variables defined by the class. (And "logical" versus "physical" is stretching it, since an object representation is only bit patterns help in some memory device.) – Stephen C Dec 25 '16 at 11:06
  • @StephenC what could be the other difference then? –  Dec 25 '16 at 11:33
  • See my Answer. This question cannot be answered properly by just talking about differences. – Stephen C Dec 25 '16 at 13:35
0

A class is a blueprint that is needed to make an object(= instance).

The difference between an object and an instance is, an object is a thing and an instance is a relation.

In other words, instance describes the relation of an object to the class that the object was made from.

-2

The definition "Object is an instance of a class", is conceptually wrong, but correct as per implementation. Actually the object oriented features are taken from the real life, for focusing the mind of programmer from more to less. In real life classes are designed to manage the object.For eg- we human beings have a caste, religion,nationality and much more. These casts, religion, nationality are the classes and have no existence without human beings. But in implementation there is no existence of objects without classes. Object- Object is an discrete entity having some well defined attribute. Here discrete mean something that makes it unique from other. Well defined attribute make sense in some context. Class- Classification of object having some common behaviour or objects of some common type.

-2

While the above answers are correct, another way of thinking about Classes and Objects would be to use real world examples: A class named Animal might contain objects like Cat, Dog or Fish. An object with a title of Bible would be of class Book, etc. Classes are general, objects are specific. This thought example helped me when I was learning Java.

kurdtpage
  • 3,142
  • 1
  • 24
  • 24
  • Yes ... but analogies can also be confusing. If `Animal` is a class and `Cat` is an instance, what is my pet pussy cat "Fluffy"? – Stephen C Dec 25 '16 at 11:08
  • In fact, in the real world (and in type theory), `Animal` denotes the set of all animals, and `Cat` denotes the set of all cats. `Cat` is a subset of `Animal` not an instance of `Animal`. – Stephen C Dec 24 '20 at 05:41
-3

Class is a template or type. An object is an instance of the class.

For example:

public class Tweet {

}

Tweet newTweet = new Tweet();

Tweet is a class and newTweet is an object of the class.

J Fabian Meier
  • 33,516
  • 10
  • 64
  • 142
Gagan
  • 93
  • 3
  • These are just words. You don't actually explain what the words mean. (And in fact, Java classes do NOT behave like templates, either in real life or in the way that the do in languages like Javascript, Python, Ruby, etc.) – Stephen C Sep 25 '16 at 02:48