Honestly, I feel more comfortable with Alfred’s blog definitions:
Object : real-world objects have two main characteristics: state and behavior. A person has a state (name, age) and behavior (running, sleeping). The car has a state (current speed, current gear) and behavior (applying the brake, shifting gears). Software objects are conceptually similar to real-world objects: they also consist of state and associated behavior. The object saves its state in the fields and reveals its behavior using methods.
Class : This is the "template" / "plan" that is used to create objects. In essence, the class will consist of a field, a static field, a method, a static method, and a constructor. The field is used to store the state of the class (for example: the name of the Student object). The method is used to represent class behavior (for example, how a student’s object is about to stand up). The constructor is used to create a new instance of the class.
Instance . An instance is a unique copy of a class that represents an object. When a new instance of the class is created, the JVM allocates memory space for this instance of the class.
Given the following 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) {
For case 1, there are two instances of the Person class, but both instances represent the same object.
For case 2, there are two instances of the Person class, but each instance represents a separate object.
So a class, an object, and an instance are two different things. An object and an instance are not synonyms, as suggested in the answer selected as the correct answer.
Carlos Casallas Jan 31 '18 at 16:42 2018-01-31 16:42
source share