why can't we assign weaker privilege in subclass

后端 未结 8 1185
挽巷
挽巷 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:23

    In dynamic method dispatch, call to overridden method is resolved at runtime rather than compile time. It based on the object being referred to at the time of the call...

    Now suppose weaker access privilege was allowed and we write the following statement in your code some other class:

    Superclass ref=new Subclass();
    ref.foo()
    

    Now during runtime, when java comes across the statement ref.foo(), it will have to call foo() of Subclass...but foo() method of subclass is declared as private in your code and private cant be called outside its own class..so now there is a conflict and it would result in runtime exception...

提交回复
热议问题