简体   繁体   中英

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.

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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