简体   繁体   English

是否可以使用具有相同名称的Java类扩展它

[英]Is it possible to extend a Java class with one having the same name

I'm working with a ridiculously large codebase and need to move a file from one package to another. 我正在使用一个非常大的代码库,需要将文件从一个包移动到另一个包。 However, I do not have the whole codebase locally, so I am not sure if I have found and updated every reference to the original file. 但是,我没有本地的整个代码库,所以我不确定我是否找到并更新了对原始文件的每个引用。 In order to ensure that I don't break anything, I would like to leave the original file, and simply have it extend the new file that I created. 为了确保我没有破坏任何东西,我想保留原始文件,并简单地扩展我创建的新文件。 Ideally, they'd both have the exact same name. 理想情况下,它们都具有完全相同的名称。 Overtime, I plan to deprecate and remove the old file, but for now this seems like the most robust solution. 加班,我打算弃用并删除旧文件,但目前这似乎是最强大的解决方案。 However, I cannot figure out how to get it to work in Java. 但是,我无法弄清楚如何让它在Java中工作。

Here is the new class: 这是新课程:

package myproject.util.http;

import javax.servlet.http.HttpServlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public abstract class MyServlet extends HttpServlet
{

    public void service (HttpServletRequest  request,
                         HttpServletResponse response)
            throws ServletException, IOException
    {
        // implementation of service
    }

}

Here is the old class that extends the new: 这是扩展新的旧类:

package myproject.util.net;

import myproject.util.http.MyServlet;

public abstract class MyServlet extends myproject.util.http.MyServlet
{
// this class was deprecated, use myproject.util.http.MyServlet instead
}

Unfortunately, I get the error: 不幸的是,我收到错误:

MyServlet is already defined in this compilation unit

Is this possible, or am I going to have to come up with a new name for the parent class. 这是可能的,还是我将不得不为父类提出一个新名称。

You can do it but you need to remove the import statement. 你可以这样做,但你需要删除import语句。

Otherwise the compilation unit will import all the classes declared in your package to be used without the fully qualified name: this means that you wouldn't be able to distinguish between the two MyServlet , this is why it is illegal. 否则编译单元将导入包中声明的所有类,而不使用完全限定名:这意味着您将无法区分两个MyServlet ,这就是为什么它是非法的。

您需要做的就是删除import语句,一切都会好的。

只需删除import并具有完全限定名称myproject.util.http.MyServlet

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

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