java - How private method of super class are resolved? -


class a{    private void saya(){      system.out.println("private method of a");   }   public static void main(string args[]){       instancea=new b();       instancea.saya();   } }  class b extends a{ } 

i expecting throw run time exception @ compile-time compiler checks if saya() can called on reference of a , @ run-time it'll check if saya() can called on b's object. instead printed "private method of a".

accessibility compile time concept (reflected in reflection apis).

from java language specification

note accessibility static property can determined @ compile time; depends on types , declaration modifiers.

that is, compiler doesn't care runtime type of instance referenced variable named instancea

a instancea = new b(); 

it cares invoked method on reference of static type a. method private , since within body of class declares it, visible, , therefore usable.

otherwise, member or constructor declared private, , access permitted if , if occurs within body of top level class (§7.6) encloses declaration of member or constructor.


for spiderman in comments, consider following

class {     private void privatemethod () {         system.out.println("private method");     }     public void publicmethod() {         privatemethod();     } }  class b extends {}  class example {     public static void main(string[] args) {         new b().publicmethod();     } } 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -