How to restrict child classes from modifying the s

2019-06-27 12:02发布

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();

    }

}

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.

3条回答
倾城 Initia
2楼-- · 2019-06-27 12:36

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.

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.

查看更多
你好瞎i
3楼-- · 2019-06-27 12:45

There is no way to do that. And I don't see the point either: if the subclass wants to make this method accessible, why shouldn't it? It won't affect users of the parent abstract class anyway.

查看更多
The star\"
4楼-- · 2019-06-27 12:58

You can't.

An overriding class can always give more access to a method than the method it's overriding.

Read the section on modifiers here http://docs.oracle.com/javase/tutorial/java/IandI/override.html

The access specifier for an overriding method can allow more, but not less, access than the overridden method. For example, a protected instance method in the superclass can be made public, but not private, in the subclass.

You will get a compile-time error if you attempt to change an instance method in the superclass to a class method in the subclass, and vice versa.

查看更多
登录 后发表回答