コンストラクタを使ってみる
class クラス名{
//コンストラクタ
クラス名(){
処理
}
}
またコンストラクタは引数を持つことも可能です
class クラス名{
//コンストラクタ
クラス名(引数1、引数2、・・・){
処理
}
}
コンストラクタに引数を付けて呼び出すには
オブジェクト作成時に
オブジェクト作成時に
クラス名 オブジェクト名 = new コンストラクタ(引数);
とします
サンプル
//りんごクラス
class Apple {
int size; //大きさ
int cnt; //数
//コンストラクタ
Apple(int m, int n){
size = m;
cnt = n;
}
String Out(int n){
System.out.println(size + "サイズのりんご" + cnt + "個");
System.out.println(n + "セット注文");
return n + "セット注文完了";
}
}
class Sample {
public static void main(String args[])
{
Apple apple0 = new Apple(50,10);
String str0 = apple0.Out(5);
System.out.println(str0);
}
}