oop - Why does the Object class in Java contain protected methods? -


why object class in java contain protected methods, such clone() , finalize(), if classes use or write inherit instance methods of object?

if class c2 extends c1, , c1 contains public method, method in c2 (if overridden) must public; java makes illegal put additional restrictions on method's access when overriding. if c1 contains protected method, overriding method in c2 may protected or public.

these rules apply if c1 object class. think reason classes (which inherit object) can declare own overriding clone , finalize methods , make them protected if choose, instead of public.

edit: important consequence of clone , finalize not freely accessible public member be. within class c2, can use clone , finalize on object of type c2 want, since protected methods , therefore available subclass c2. can't use them on objects of class.

class x { }  class y {     private y field1;     private x field2;     public void foo() throws exception {         object o1 = this.clone();      // legal         object o2 = field1.clone();    // legal         object o3 = field2.clone();    // illegal         string s1 = field2.tostring(); // legal since tostring() "public" in object     } } 

this should demonstrate although protected methods accessible subclasses, there still restrictions on how accessible are. note if x had @override public object clone() method, declaration of o3 become legal.


Comments

Popular posts from this blog

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -

python 3.x - Mapping specific letters onto a list of words -