如何限制子类修改Abstract类中方法的范围? [英] How to restrict child classes from modifying the scope of a method in Abstract class?

查看:90
本文介绍了如何限制子类修改Abstract类中方法的范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何限制Abstract类的实现类将方法的范围从受保护范围更改为公共范围?

How can I restrict the implementation class of my Abstract class from modifying the scope of a method from protected to public?

例如:假设我有一个抽象类

For example : Suppose I have a Abstract Class

package com.rao.test;

public abstract  class AbstractTEClass {

    protected abstract void function1();

    protected abstract void function2();


    protected void doWork() //I want to call the abstract methods from this method.
    {
        function1(); //implementation classes will give implementation of these methods
        function2();

    }

}

现在,我有一个实现类,它扩展了上面的抽象类

Now, I have a implementation class which extends the above abstract class

package com.rao.test;

public class AbstractTEClassImpl extends AbstractTEClass {

    @Override
    public void function1() {
        // TODO Auto-generated method stub
        System.out.println("FUnction1");
    }

    @Override
    public void function2() {
        // TODO Auto-generated method stub
        System.out.println("Function2");
    }


    public static void main(String[] args)
    {
        AbstractTEClassImpl objTEClass = new AbstractTEClassImpl();

        objTEClass.doWork();

    }

}

请注意,我正在将实现类中的2个抽象方法的范围从保护更改为公共,如何限制实现类修改范围.
欢迎进行任何设计更改,推荐或模式.

Notice here that I am changing the scope of the 2 abstract methods in the implementation class from protected to public, how can I restrict my implementation class from modifying the scope.
Any design changes or recommendation or patterns are welcome.

推荐答案

您不能.我怀疑您想做的是弄弄doWork(),这样它就可以在扩展类可能在function1和2覆盖内部进行的任何滥用中幸存下来.您可能想要添加方法和/或更改这些方法的功能.

You can't. I suspect what you want to do is fiddle with doWork() so it can survive any abuse extending classes might do inside the function1 and 2 overrides. You might want to add methods and/or change what those methods do.

覆盖是一件方便的事情.我经常对使用C#感到非常恼火,因为Microsoft会对所有内容进行密封"以防止覆盖. (我夸大了;它们只密封要覆盖的方法 I .)不要走那条路.找出真正的问题是什么,并在基本AbstractTEClass类中进行处理.

Overriding is a handy thing. I often get real annoyed working in C# because Microsoft "seals" everything to prevent overriding. (I exaggerate; they only seal the methods I want to override.) Don't go that route. Figure out what your real problem is and handle it in your base AbstractTEClass class.

这篇关于如何限制子类修改Abstract类中方法的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆