Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความแตกต่างระหว่าง Constructors และ Methods ใน Java

Constructors เป็น special methods ใช้ initialize objects ส่วน methods ใช้ execute statements ความแตกต่าง:

ลำดับ หัวข้อ Constructors Methods
1 Purpose สร้างและ initialize object execute statements
2 Invocation ถูกเรียกโดย system โดยอัตโนมัติ (implicit) ต้องเรียกในโค้ด explicitly
3 When Invoked ตอนใช้ new keyword สร้าง object ตอนถูกเรียกในโค้ด
4 Return Type ไม่มี return type มี return type
5 Object initialize object ที่ยังไม่มีอยู่ invoke บน object ที่มีอยู่แล้ว
6 Name ต้องชื่อเดียวกับ class ห้ามชื่อเดียวกับ class
7 Inheritance สืบทอดไม่ได้ สืบทอดได้

ตัวอย่าง

public class JavaTester {
    int num;
    JavaTester() {
        num = 3;
        System.out.println("Constructor invoked. num: " + num);
    }
    public void init() {
        num = 5;
        System.out.println("Method invoked. num: " + num);
    }
    public static void main(String args[]) {
        JavaTester tester = new JavaTester();
        tester.init();
    }
}

ผลลัพธ์

Constructor invoked. num: 3
Method invoked. num: 5