Class 基于 class 的变量 - 不清楚

Class variable based on a class - unclear

我在 class 中有以下方法,但我不明白它的用途:

private PageInfo getPage(){}(注意 PageInfo 是大写的)。

PageInfo 是一个 class,这使得它有所不同,因为 getter 通常在 class.

的方法中使用

我可以创建一个 Class 变量作为:private PageInfo 页面; 然后我可以为它创建一个 getter 作为: public PageInfo getWebpage() {return webpage;}

但是,尚不清楚其目的和原因。 非常感谢您的回复并提前致谢!

private PageInfo getWebPage(URL url, URL parentUrl) throws IOException
{
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    int responseCode = connection.getResponseCode();
    String contentType = connection.getContentType();
    // Note: contentLength == -1 if NOT KNOWN (i.e. not returned from server)
    int contentLength = connection.getContentLength();  
    PageInfo p = new PageInfo(url,parentUrl,contentType,contentLength,responseCode);
    InputStreamReader rdr =
        new InputStreamReader(connection.getInputStream());
    p.extract(rdr);
    rdr.close();
    connection.disconnect();
    return(p);
}

已解决:

上面的方法写在不同的class中,方法名前面是其class的名称。该方法的名称不符合命名约定(不需要)。它的方法访问修饰符默认为 void 因为没有声明任何修饰符,因此它应该不会 return 任何东西但是有一个接受规则。据此它可以return 初始化其Class PageInfo。否则,可以设置为return null (return: null;).

private MyClass getInfo() {
    int e = 300;
    int t = 10;
    MyClass z = new MyClass(22);

    return  z; // z is the initialization of MyClass  
               // return null; is also valid 

}

听起来您希望此方法成为基于其命名约定的访问器。

相反,它看起来像是一个私有辅助方法,用于从提供的 url 生成 PageInfo 对象(实际上它调用了一个需要额外参数的构造函数,它从提供的参数派生)。如果没有看到更大的上下文,我无法确切地告诉你目的是什么,但它肯定不会做你用你的私有 class 变量和 public 访问器示例描述的同样的事情。

希望这对您有所帮助 - 如果没有,我建议您澄清您的问题,或提供额外的代码。

编辑:您用 intellij-idea 标记了它 - 如果您使用的是 IDE,请尝试突出显示方法名称并按 alt-f7 查找用法。这应该让您了解调用此方法的位置和原因。