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
<code class="java">// 定义一个类 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();</code>
In the above example, the Person
class defines age
and name
Properties and introduce()
methods. A John
object is an instance of the Person
class, has its own age
and name
values, and can call introduce()
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!