java 向上转型有什么用? 财富值66

2016-10-27 02:03发布

1.问题描述

向下转型的应用场景是面向接口编程的时候,经常需要向下转型。但是向上转型的应用场景是什么呢?

我看到网上有的说是为了获取父类的方法,子类也可以访问父类的方法啊,就算是覆盖的方法,也可以通过super.方法()来访问父类的方法啊。

2.代码

代码来源是《深入剖析Tomcat》第二章的代码。

package ex02.pyrmont;  import java.net.URL; import java.net.URLClassLoader; import java.net.URLStreamHandler; import java.io.File; import java.io.IOException; import javax.servlet.Servlet; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse;  public class ServletProcessor1 {      public void process(Request request, Response response) {          String uri = request.getUri();         String servletName = uri.substring(uri.lastIndexOf("/") + 1);         URLClassLoader loader = null;          try {             // create a URLClassLoader             URL[] urls = new URL[1];             URLStreamHandler streamHandler = null;             File classPath = new File(Constants.WEB_ROOT);             // the forming of repository is taken from the createClassLoader             // method in             // org.apache.catalina.startup.ClassLoaderFactory             String repository = (new URL("file", null,                     classPath.getCanonicalPath() + File.separator)).toString();             // the code for forming the URL is taken from the addRepository             // method in             // org.apache.catalina.loader.StandardClassLoader class.             urls[0] = new URL(null, repository, streamHandler);             loader = new URLClassLoader(urls);         } catch (IOException e) {             System.out.println(e.toString());         }         Class myClass = null;         try {             myClass = loader.loadClass(servletName);         } catch (ClassNotFoundException e) {             System.out.println(e.toString());         }          Servlet servlet = null;          try {             servlet = (Servlet) myClass.newInstance();             servlet.service((ServletRequest) request,                     (ServletResponse) response); //注:Request实现了ServletRequest接口,这里为什么要向上转型呢?         } catch (Exception e) {             System.out.println(e.toString());         } catch (Throwable e) {             System.out.println(e.toString());         }      } }
友情提示: 问题已经关闭,关闭后问题禁止继续编辑,回答。
该问题目前已经被作者或者管理员关闭, 无法添加新回复
0条回答

一周热门 更多>