在java中构造函数后运行代码?

时间:2016-10-25 01:02:55

标签: java constructor

我想将“种子”值传递给构造函数,然后根据该种子值创建一个Random变量。我不知道该怎么做。以下是我的观点:

public void showNotification() {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setSmallIcon(R.drawable.sheikoicon);
    builder.setContentTitle("Sheiko Rest Timer");
    builder.setContentText("Rest timer is up, start your set!");
    builder.setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_VIBRATE);
    builder.setAutoCancel(true);
    Intent intent = new Intent(context, MyWorkout.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(MyWorkout.class);
    stackBuilder.addNextIntent(intent);
    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(pendingIntent);
    NotificationManager NM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    NM.notify(0, builder.build());
}

从主要类我创建的“Die”变量如下:

public class Die
{

    private int seed;
    Random _randNum = new Random(seed);

    public Die(int seed) { this.seed = seed; }
}

基本上,我希望“种子”值在

时为5
private Die _die1 = new Die(5);

跑了。关于如何实现这一点的任何想法?

1 个答案:

答案 0 :(得分:4)

更改代码,以便在构造函数

中实例化_randNum

e.g

public class Die
{
    private int seed;
    Random _randNum;

    public Die(int seed) { 
       this.seed = seed;  // actually no need to keep this value
       _randNum = new Random(seed);
    }
}