为什么可以直接使用 ServletContext context=getServletConfig().getServletContext();

一、问题

最近在重新学习JavaWeb,对于以下代码不是很理解:

public class HelloServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet2的doGet方法");
//        1、获取 web.xml 中配置的上下文参数 context-param
        ServletContext context=getServletConfig().getServletContext();
        String username=context.getInitParameter("username");
        System.out.println("context-param参数username的值是:"+username);
        System.out.println("context-param参数password的值是:"+1);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("HelloServlet2的doPost方法");

    }
}

如上,为什么getServletConfig()可以直接调用呢,不应该先对类进行实例化,再调用对象的方法吗?

二、原因

分析HelloServlet2的继承关系,可以发现其最终继承的类为GenericServlet类,该类中存在着方法getServletConfig()。根据继承关系,子类HelloServlet2可以调用父类的方法getServletConfig()。
在这里插入图片描述

三、思考

示例如下:
定义抽象类Animal

package com.coderp.test;

/**
 * @program: 06_web
 * @description: 动物
 * @author: CoderP
 * @create: 2021-04-27 11:14
 **/
public abstract class Animal {

    public int eat(){
        System.out.println("animal eating.....");
        return 1;
    }
}

peopel类继承animal类

package com.coderp.test;

import org.junit.Test;


/**
 * @program: 06_web
 * @description:
 * @author: CoderP
 * @create: 2021-04-27 11:15
 **/
public class People extends Animal {
    int i=eat();
    @Test
    public void test() {
        System.out.println(i);
    }
}

输出结果如下:
在这里插入图片描述

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值