Javaで抽象クラスのオブジェクトを作成できますか?
いいえ、抽象クラスのオブジェクトを作成することはできません。ただし、抽象クラスの参照変数を作成することはできます。参照変数は、派生クラス(抽象クラスのサブクラス)のオブジェクトを参照するために使用されます。
抽象クラスとは、実装を非表示にし、関数定義をユーザーに表示することを意味し、抽象クラスと呼ばれます。 Java抽象クラスには、要件がわかっていて、抽象クラスに部分的に実装できる場合に、デフォルトの動作を実装するインスタンスメソッドを含めることができます。
例
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());
}
} 上記の例では、Diagramタイプのオブジェクトを作成することはできませんが、Diagramタイプの参照変数を作成することはできます。ここでは、Diagramタイプの参照変数を作成し、Diagramクラス参照変数を使用してRectangleクラスとTriangleクラスのオブジェクトを参照しています。
出力
Inside Area for Rectangle. Area of Rectangle is: 45.0 Inside Area for Triangle. Area of Triangle is:40.0
-
列挙型はJavaの任意のクラスを拡張できますか?
Javaの列挙(enum)は、定数値のセットを格納するデータ型です。列挙型を使用して、1週間の日数、1年の月数などの固定値を格納できます。 キーワードenumの後に列挙型の名前を-として使用して、列挙型を定義できます。 enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } 配列と同様に、列挙型の要素/定数は、上記の例では0から始まる番号を使用して識別されます。日は、次の図に示すように番号を使用して識別されます- 列挙型はクラスに似ており、変数、メソッド、コン
-
JSONオブジェクトからPythonクラスを作成するにはどうすればよいですか?
jsonschemaの上に構築されたpython-jsonschema-objectsを使用できます。python-jsonschema-objectsは、Pythonで使用するためのJSONスキーマへの自動クラスベースバインディングを提供します。 次のようなサンプルのjsonスキーマがあります schema = '''{ "title": "Example Schema", "type": "object",