为了账号安全,请及时绑定邮箱和手机立即绑定

java 向上转型有什么用?

java 向上转型有什么用?

慕妹3242003 2019-03-20 16:15:42
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());        }
查看完整描述

4 回答

?
忽然笑

TA贡献1806条经验 获得超5个赞

向上转型是为了用父类变量来接受不同的子类对象,调用方法的时候传参父类对象,可以调用子类里不同的重写方法,得到不同的结果。


查看完整回答
1 反对 回复 2019-04-25
?
温温酱

TA贡献1752条经验 获得超4个赞

查看完整回答
反对 回复 2019-04-25
?
杨__羊羊

TA贡献1943条经验 获得超7个赞

这行代码将 Request 和 Response 类型的参数强制转换为 ServletRequest 和 ServletResponse,这不是向上,仍然是向下。强制类型转换与变量本身的类型有关,而与变量所指向的对象的实际类型无关。


查看完整回答
反对 回复 2019-04-25
?
SMILET

TA贡献1796条经验 获得超4个赞

这个不叫向上转型,只是一个显式的类型转换吧


查看完整回答
反对 回复 2019-04-25
  • 4 回答
  • 0 关注
  • 1121 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号