gpt4 book ai didi

java - java中的静态方法,我可以以非静态方式访问静态方法吗?

转载 作者:行者123 更新时间:2023-12-01 17:05:53 25 4
gpt4 key购买 nike

我认为我的代码有问题,以静态方式或以非方式调用(在 setIstance 中)方法 isSameMonth() 是否相同静态方式?编译器建议我将 timesheet.isSameMonth() 更改为 Timesheet.isSameMonth()

我认为不可以,因为我想传递本地变量timesheet,这是同样的事情还是我应该修改我的代码?

时间表类别:

static private Timesheet timesheet;

static public Timesheet getIstance()
{
if (timesheet == null || !Timesheet.isSameMonth())
{
timesheet = null;
timesheet = new Timesheet();
}
return timesheet;
}

static public void setIstance(Timesheet timesheet)
{
if (timesheet != null && timesheet.isSameMonth())
{
Timesheet.timesheet = timesheet;
}
}

public static boolean isSameMonth()
{
Date now = new Date();
Calendar calendarNow = Calendar.getInstance();
calendarNow.setTime( now );
Date firstDay = timesheet.days[0];
Calendar calendarFirstDay = Calendar.getInstance();
calendarFirstDay.setTime( firstDay );
if (calendarNow.get(Calendar.MONTH) == calendarFirstDay.get(Calendar.MONTH))
{
return true;
}
return false;
}

我从外部调用此电话:

Gson gson = new Gson();
String json = sharedPrefs.getString("timesheet", "");
if (!json.isEmpty())
{
try
{
Timesheet timesheet = Timesheet.getIstance();
if (timesheet.getDay(0)==null)
{
Timesheet.setIstance( gson.fromJson(json, Timesheet.class) );
}
refreshWidget(timesheet, context, allWidgetIds, intent.getAction());
}
catch (Exception e)
{
Log.e(TAG_LOG, e.toString());
}
}

最佳答案

无论哪种方式都可以工作,但约定是通过类名引用静态方法:

Timesheet.isSameMonth()

这可以让阅读您代码的人清楚地知道您正在调用静态方法。

关于java - java中的静态方法,我可以以非静态方式访问静态方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25604832/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com