Is inheritance time or runtime in java

I was told that inheritance is runtime, but I want to ask that if inheritance is runtime, how does the compiler generate an error at compile time when we try to access the data member of the parent class through the object of the child class:

class PrivateData {
    private int x = 50;

    void show() {
        System.out.println(x);
    }
}

class ChildPrivateData extends PrivateData {

    public static void main(String s[]) {
        ChildPrivateData c1 = new ChildPrivateData();
        System.out.println(c1.x);
    }
}
+4
source share
3 answers

Inheritance is most specifically defined at compile time in Java. I think you mix it with polymorphism, which, in a nutshell, claims that Java chooses which overridden method to run only at runtime.

+2
source

. . .

String result = returnInt();  // #1

public int returnInt() {
 return 1;
}

, #1 , returnInt(), ? ?

, . .

+1

java "extends", . Base private.A . .

class PrivateData{
  private int x =50;

  void show(){
    System.out.println(x);
  }
}

class ChildPrivateData extends PrivateData {

  public static void main(String s[]){
      ChildPrivateData  c1 = new ChildPrivateData();
      System.out.println(c1.show());
  }
}
0

Source: https://habr.com/ru/post/1611982/


All Articles