Classes are templates, objects are instances; classes define properties and methods, and objects have their own properties and states; classes are stored in the method area, and objects are stored in the heap.
The difference between classes and objects
In Java, classes and objects are object-oriented programming (OOP) Two basic concepts. The main differences between them are as follows:
Definition
Creation method
class
keyword, just like a class declaration.new
keyword, which allocates memory and calls the class's constructor.Attributes
Method
Object state
Memory Management
Example
// 定义一个类 class Person { int age; String name; // 构造函数 public Person(int age, String name) { this.age = age; this.name = name; } // 方法 public void introduce() { System.out.println("Hi, I am " + name + " and I am " + age + " years old."); } } // 创建一个对象 Person John = new Person(20, "John Doe"); // 访问对象属性和调用方法 John.introduce();
In the above example, thePerson
class definesage
andname
Properties andintroduce()
methods. AJohn
object is an instance of thePerson
class, has its ownage
andname
values, and can callintroduce()
method.
The above is the detailed content of The difference between classes and objects in java. For more information, please follow other related articles on the PHP Chinese website!