Junior — Middle
What is the difference between a class member function and a special method for object initialization?
sobes.tech AI
Answer from AI
In Java, a class member function is a regular method defined inside a class and can be called on an object of that class. A special method for initializing objects is a constructor.
Differences:
- Constructor is called automatically when an object is created using
newand is used to initialize the object's state. - Constructor has no return type, not even
void. - The constructor's name matches the class name.
- A member function can have any name, return values, and can be called at any time after the object is created.
Example:
class Person {
String name;
// Constructor
Person(String name) {
this.name = name;
}
// Regular method
void sayHello() {
System.out.println("Hello, my name is " + name);
}
}
Person p = new Person("Ivan"); // calling constructor
p.sayHello(); // calling method