why can't we assign weaker privilege in subclass

后端 未结 8 1247
挽巷
挽巷 2020-12-09 10:53

I have a class which has a method whose access specifier by default is public. Now, I would like to extend this class in a subclass and I want to override this method to hav

8条回答
  •  难免孤独
    2020-12-09 11:22

    I think the short answer is that the compiler writers have set the rules to work this way. LSP has nothing to do with the problem at hand.

    The only reason I can think of to have this restriction is that when a subclass derives from an interface, as a client programmer, you expect to be able to call all the accessible methods of the interface from a reference to the derived class.

    Just suppose that you could write the code that the OP has shown. If you have a reference to the derived class you should be able to call any public members of the derived class (though there are none in this case). However, pass the reference as a parameter to a method which takes a reference to the base class and the method will expect to call any public or package method, which is foo. This is the LSP that other contributors are looking for!

    C++ example:

    class Superclass{
    public:
    virtual void foo(){ cout << "Superclass.foo" << endl; }
    };
    
    class Subclass: public Superclass{
    virtual void foo(){ cout << "Subclass.foo" << endl; }
    };
    
    int main(){
    Superclass s1;
    s1.foo() // Prints Superclass.foo
    
    Subclass s2;
    // s2.foo();  // Error, would not compile
    
    Superclass& s1a=s2; // Reference to Superclass 'pointing' to Subclass
    
    s1a.foo(); // Compiles OK, Prints Subclass.foo()
    }
    

提交回复
热议问题