public class Counter {
static int num = 0;
static int getCounter(){
return ++num;
}
}実行してみる
public class SandBox extends Counter {
public static void main(String[] args){
System.out.println(Counter.getCounter());
System.out.println(Counter.getCounter());
System.out.println(Counter.getCounter());
System.out.println("クラスフィールド:" + Counter.num);
}
}実行結果:
1 2 3 クラスフィールド:3
perlで表現してみます。
package Counter;
use strict;
use warnings;
our $num = 0;
sub getCounter{
return ++$num;
}
1;use strict; use warnings; use utf8; use feature 'say'; binmode STDOUT, ":utf8"; use lib qw(lib); use Rectangle; use Counter; say Counter::getCounter(); say Counter::getCounter(); say Counter::getCounter(); say "クラス内変数:". $Counter::num;
実行結果:
1 2 3 クラス内変数:3
たいした違いはないですね。
クラス内の変数にアクセスするためにourで宣言しています。
0 件のコメント:
コメントを投稿