The difference between Classes, Objects, and Instances

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

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

相关标签:
16条回答
  • 2020-11-22 06:33

    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.

    0 讨论(0)
  • 2020-11-22 06:34

    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

    0 讨论(0)
  • 2020-11-22 06:34

    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

    0 讨论(0)
  • 2020-11-22 06:35

    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.

    0 讨论(0)
提交回复
热议问题