简体   繁体   English

为什么不能在类的构造函数中调用静态方法?

[英]Why can't I call a static method in the constructor of a class?

obviously my Java Pause was too long... 显然我的Java暂停太长了...

I have the following classes: 我有以下课程:

public class TimeLine {

    public static final String TIME_LINE_DATE_FORMAT = "dd.MM.yyyy";


    public TimeLine(Context context, LinearLayout layout)
    {
        this.context = context;
        this.layout = layout;           
    }

    // some methods and stuff

    public static Date getDateFromString(String dateString)
    {
        SimpleDateFormat s = new SimpleDateFormat(TIME_LINE_DATE_FORMAT);
        try {
            return s.parse(dateString);
        } catch (ParseException e) {            
            e.printStackTrace();
            return null;
        }
    }
}

I use the parsing of a String to a Date quite often, that's why I wanted to have this function only 1 time & static. 我经常使用将字符串解析为Date的功能,这就是为什么我只想让此函数具有1次静态的原因。

I try to access it like this: 我尝试像这样访问它:

public class TrackedValue {

    private double value;
    private String unit;
    private Date date;

    public TrackedValue()
    {       
    }

    public TrackedValue(Date date, String unit, double value)
    {
        this.date = date;
        this.unit = unit;
        this.value = value;
    }

    public TrackedValue(String dateString, String unit, double value)
    {      
        this.date = TimeLine.getDateFromString(dateString); //Here's the error
        this.unit = unit;
        this.value = value;
    }

    // some getters and setters here

}

This brings me the error: The method getDateFromString(String) is undefined for the type timeline 这给我带来了错误: 类型timeline的方法getDateFromString(String)未定义

Err... why? 嗯...为什么?

Look at your imports section. 查看您的进口部分。

Is YOUR timeline class referenced there or is there another from some other jar you have imported to your application? 是在那里引用了您的时间轴类,还是在导入到应用程序的其他jar中有另一个?

Why can't I call a static method in the constructor of a class?

You can call static method in your constructor and no one can stop you unless you don't have access to the method like access modifier restriction. 您可以在构造函数中调用静态方法,除非您没有访问限制修饰符之类的方法,否则没有人可以阻止您。

There could be problem in your import statement .Please check TimeLine class is there or is this imported correctly. 您的import语句中可能存在问题。请检查是否存在TimeLine类或此导入是否正确。

dah ... TimeLine没有保存,因此没有被编译...我现在有点愚蠢:-/谢谢大家!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM