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

สามารถสร้าง Object ของ Abstract Class ใน Java ได้หรือไม่?

ไม่สามารถ เรา ไม่สามารถสร้าง object ของ abstract class ได้ แต่เราสามารถสร้าง reference variable ของ abstract class ได้ Reference variable ใช้เพื่ออ้างอิงถึง objects ของ derived classes (subclasses ของ abstract class)

Abstract class หมายถึงการซ่อน implementation และแสดงแค่ function definition ให้ผู้ใช้ Java abstract class สามารถมี instance methods ที่ implement default behavior ได้ หากเรารู้ requirement และต้องการ partially implementation สามารถใช้ abstract class ได้

ตัวอย่าง

abstract class Diagram {
    double dim1;
    double dim2;
    Diagram(double a, double b) {
        dim1 = a;
        dim2 = b;
    }
    // area is now an abstract method
    abstract double area();
}
class Rectangle extends Diagram {
    Rectangle(double a, double b) {
        super(a, b);
    }
    // override area for rectangle
    double area() {
        System.out.println("Inside Area for Rectangle.");
        return dim1 * dim2;
    }
}
class Triangle extends Diagram {
    Triangle(double a, double b) {
        super(a, b);
    }
    // override area for triangle
    double area() {
        System.out.println("Inside Area for Triangle.");
        return dim1 * dim2 / 2;
    }
}
public class Test {
    public static void main(String args[]) {
        // Diagram d = new Diagram(10, 10); // illegal now
        Rectangle r = new Rectangle(9, 5);
        Triangle t = new Triangle(10, 8);
        Diagram diagRef; // This is OK, no object is created
        diagRef = r;
        System.out.println("Area of Rectangle is: " + diagRef.area());
        diagRef = t;
        System.out.println("Area of Triangle is:" + diagRef.area());
    }
}

ในตัวอย่างข้างต้น เราไม่สามารถสร้าง object ของ Diagram ได้ แต่เราสามารถสร้าง reference variable ของ Diagram ได้ ที่นี่เราสร้าง reference variable ของ Diagram และ Diagram class reference variable ใช้เพื่ออ้างอิงถึง objects ของ Rectangle และ Triangle class

ผลลัพธ์

Inside Area for Rectangle.
Area of Rectangle is: 45.0
Inside Area for Triangle.
Area of Triangle is:40.0