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

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

Class

Class เป็น blueprint สร้าง objects มี variable 3 ประเภท:

  • Local variables: ใน methods/constructors/blocks ประกาศ init ใน method ทำลายเมื่อ method จบ
  • Instance variables: ในคลาสนอก method init ตอน instantiate เข้าถึงได้จากทุก method/constructor/block ของคลาสนั้น
  • Class variables: ในคลาสนอก method มี static keyword

Interface

Interface เป็น reference type คล้าย class เป็นกลุ่ม abstract methods Class implements interface จะสืบทอด abstract methods นั้น

อาจมี constants, default methods, static methods, nested types Method body มีได้เฉพาะ default และ static methods

เขียน interface คล้าย class แต class อธิบาย attributes และ behaviors ของ object ส่วน interface มี behaviors ที่ class implements

ลำดับ หัวข้อ Class Interface
1 Supported Methods มี abstract และ concrete methods ได้ มีแค่ abstract methods (Java 8+ มี default/static ได้)
2 Multiple Inheritance ไม่รองรับ รองรับ
3 Supported Variables final, non-final, static, non-static static และ final เท่านั้น
4 Implementation Class implement interface ได้ Interface implement interface ไม่ได้ (extend ได้)
5 Keyword class interface
6 Inheritance extends class และ implements interface extends interface เท่านั้น
7 Inheritance (be inherited) extends class implements interface
8 Access Modifiers private, public, protected, default public เท่านั้น
9 Constructor มี constructor ได้ ไม่มี constructor

ตัวอย่าง

public class JavaTester {
    public static void main(String args[]) {
        Animal tiger = new Tiger();
        tiger.eat();
        Tiger tiger1 = new Tiger();
        tiger1.eat();
    }
}

interface Animal {
    public void eat();
}

class Tiger implements Animal {
    public void eat() {
        System.out.println("Tiger eats");
    }
}

ผลลัพธ์

Tiger eats
Tiger eats