The difference between Classes, Objects, and Instances

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

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

16条回答
  •  感动是毒
    2020-11-22 06:20

    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.

提交回复
热议问题