The difference between Classes, Objects, and Instances

前端 未结 16 1770
耶瑟儿~
耶瑟儿~ 2020-11-22 05:32

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

16条回答
  •  不思量自难忘°
    2020-11-22 06:19

    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.

提交回复
热议问题